1

.aspx page:

<script type="text/javascript">
        $(document).ready(function () 
        {
            $('********').click(function (id) 
            {
                var test = "test";
                $.ajax(
                {
                    type: "POST",
                    url: "*************",
                    data: { type: test },
                    dataType: "string",               
                    success: function (data) { show(data); },
                    failure: function () { alert("Failed"); }
                });
            });
        });

        function show(data)
        {
            alert("Worked");
        }
</script>

Controller function:

[HttpPost]
public ActionResult getTest(String type)
{
     List<Test> test = new List<Test>();
     SqlConnection con = new SqlConnection("*****************");
     SqlCommand cmd = new SqlCommand("****************");
     cmd.Connection = con;
     cmd.Connection.Open();
     SqlDataReader reader = cmd.ExecuteReader();

     int i = 0;
     while (reader.Read())
     {
          test.Add(new Test{ itemName = reader.GetString(0),
                             itemType = reader.GetString(1),
                             itemClass = reader.GetString(2),
                             imageURL = reader.GetString(3)});
     }
     var test = Json(test, JsonRequestBehavior.AllowGet);
     return test;
}

I changed names of stuff around in the code, but anyways when I run the website and click on the div it contacts the controller and returns the correct json object(put breakpoint in at the return line to verify what test was filled with). Nothing is ever returned to the webpage though. In the web browser debugger I put a breakpoint in the ajax function and that hits, but when I hit continue it never hits the breakpoint I put in the show function. Also it does not show the alert("error") either and when I take the data out or change the url it will show the error alert.

Things I have tried...

Changing the controller type to JsonResult - controller returns same thing, but never gets back to the page.

Tried adding a contentType to the ajax function - causes the controller to never get even get called. No matter what value I put in. "application/json; charset=utf-8" <- this one does not work.

Tried the shorthand version of ajax where you just put success: show.

5 Answers 5

1

I figured it out... I changed the return type of the controller function to String and then use the JavaScript serializer to turn the list of models I had created into a JSON string that could be passed back to the ajax function on the view. Also I removed the dataType in the ajax function, since ajax is able to auto figure out what the return type is mostly.

JavaScript:

<script type="text/javascript">
        $(document).ready(function () 
        {
            $('********').click(function (id) 
            {
                var test = "test";
                $.ajax(
                {
                    type: "POST",
                    url: "*************",
                    data: { type: test },               
                    success: function (data) { show(data); },
                    failure: function () { alert("Failed"); }
                });
            });
        });

        function show(data)
        {
            alert("Worked");
        }
</script>

Controller:

[HttpPost]
public String getTest(String type)
{
     List<Test> test = new List<Test>();
     SqlConnection con = new SqlConnection("*****************");
     SqlCommand cmd = new SqlCommand("****************");
     cmd.Connection = con;
     cmd.Connection.Open();
     SqlDataReader reader = cmd.ExecuteReader();

     int i = 0;
     while (reader.Read())
     {
          test.Add(new Test{ itemName = reader.GetString(0),
                             itemType = reader.GetString(1),
                             itemClass = reader.GetString(2),
                             imageURL = reader.GetString(3)});
     }
     System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new     System.Web.Script.Serialization.JavaScriptSerializer();
     var temp = jSearializer.Serialize(test);
     return temp;
}

This code returned a JSON object to the view that I could then use like an array of objects, so I could add multiple divs to my view for each object and then write the objects values to the divs as well.

Sign up to request clarification or add additional context in comments.

Comments

0

Get rid of this line from your AJAX request:

dataType: "string", 

Your controller returns JSON, so make sure that you specify the correct type:

dataType: "json", 

But since jQuery is intelligent enough to use the Content-Type response header to guess the correct content type you can simply remove it.

Also IIRC, the error function is called error instead of failure.

8 Comments

Tried that... also tried changing it to dataType: "json" Still hits the controller but the return value does not get passed back to the ajax function
OK, now look at the console of your web browser. Do you seen any errors?
If there are no errors and you can see the response JSON from the server then there's no reason why the success callback won't be invoked.
Can you see the AJAX request returning JSON in the Network tab?
throwing this error now... SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3. when i changed to alert(error)
|
0

You need add:

 contentType: 'application/json; charset=utf-8',

Example:

  $.ajax({
        url: 'PUT_YOUR_URL_HERE',
        dataType: "json",
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ Make: maka.value }),
        async: true, // Or false           
        cache: false,
        success: function (data) {
           //do something
            }

        },
        error: function (xhr) {
            alert('error');
        }
    })

7 Comments

And in future - You must separate DAL - BL - UI
This got it to work. I don't know which change I needed or if I needed it all. I will go through it changing each line back one at a time and see when it breaks and post my findings.
actually this didn't work. It hit the success function, because changing the data type passed in a null value to the controller. If i keep all the other changes and just change back to data: {type: test} it throws the same console error. So apparently it doesn't like having a string passed from the ajax to the controller.
also what is BL - DAL - UI?
also i tried other variations of JSON.stringify(changing whats in here) and it always ends up passing a null value to the controller.
|
0

Try this. "dataType" is what you send, "accepts" is what your query accepts.

$.ajax({
    url: 'PUT_YOUR_URL_HERE',
    dataType: "json",
    accepts:"application/json",
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ Make: maka.value }),
    async: true, // Or false           
    cache: false,
    success: function (data) {
       //do something
        }

    },
    error: function (xhr) {
        alert('error');
    }
});

Comments

0

I was struggling with a similar issue today: JSON object was always null.

    var id = $('#ModalCategoryId').val();
    var category = $.trim($('#ModalCategory').val());

    var categoryJson = new Object();
    categoryJson.CategoryId = id;
    categoryJson.Category = category;
    var data = JSON.stringify(categoryJson);

    $.ajax({
        "url": SAVE_CATEGORY_URL,
        data: data,
        type: "POST",
        dataType: 'json',
        traditional: true,
        contentType: 'application/json; charset=utf-8',

and the controller action method declaration:

    [HttpPost]
    public ActionResult SaveCategory(CategoryLookupUIObject category)

the json would always show up as null UNTIL I changed the parameter name to something besides "category." Apparently having a Category property on my object and having the parameter also called category was blowing it up. As soon as I changed it to e.g:

    [HttpPost]
    public ActionResult SaveCategory(CategoryLookupUIObject categoryLookup)

it started passing a view model object instead of null. Any parameter name works, except "category".

I noticed the OP had a property called Type and also the name of his parameter on the controller was "type", so I felt compelled to point out that this was the source of the problem in my case; perhaps for the OP as well?

Good luck!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.