[json] Parse JSON from JQuery.ajax success data

I am having trouble getting the contents of JSON object from a JQery.ajax call. My call:

$('#Search').click(function () {
    var query = $('#query').valueOf();
    $.ajax({
        url: '/Products/Search',
        type: "POST",
        data: query,
        dataType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data);
            for (var x = 0; x < data.length; x++) {
                content = data[x].Id;
                content += "<br>";
                content += data[x].Name;
                content += "<br>";
                $(content).appendTo("#ProductList");
               // updateListing(data[x]);
            }
        }
    });
});

It seems that the JSON object is being returned correctly because "alert(data)" displays the following

[{"Id": "1", "Name": "Shirt"}, {"Id": "2", "Name":"Pants"}]

but when I try displaying the Id or Name to the page using:

content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";

it returns "undefined" to the page. What am I doing wrong?

Thanks for the help.

This question is related to json jquery

The answer is


you can use the jQuery parseJSON method:

var Data = $.parseJSON(response);

Try the jquery each function to walk through your json object:

$.each(data,function(i,j){
    content ='<span>'+j[i].Id+'<br />'+j[i].Name+'<br /></span>';
    $('#ProductList').append(content);
});

input type Button

<input type="button" Id="update" value="Update">

I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below

$(function() {

    $('#Search').click(function() {
        var query = $('#query').val();
        var update = $('#update').val();

        $.ajax({
            type: 'POST',
            url: '/Products/Search/',
            data: {
                'insert': update,
                'query': address,
            },
            success: function(res) {
                $('#ProductList').empty('');
                console.log(res);
                json = JSON.parse(res);
                for (var i in json) {
                    var row = $('<tr>');
                    row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
                    row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
                    $('</tr>');
                    $('#ProductList').append(row);
                }
            },
            error: function() {
                alert("did not work");
                location.reload(true);
            }
        });
    });
});

I recommend you use:

var returnedData = JSON.parse(response);

to convert the JSON string (if it is just text) to a JavaScript object.


From the jQuery API: with the setting of dataType, If none is specified, jQuery will try to infer it with $.parseJSON() based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).

Or you can set the dataType to json to convert it automatically.


Well... you are about 3/4 of the way there... you already have your JSON as text.

The problem is that you appear to be handling this string as if it was already a JavaScript object with properties relating to the fields that were transmitted.

It isn't... its just a string.

Queries like "content = data[x].Id;" are bound to fail because JavaScript is not finding these properties attached to the string that it is looking at... again, its JUST a string.

You should be able to simply parse the data as JSON through... yup... the parse method of the JSON object.

myResult = JSON.parse(request.responseText);

Now myResult is a javascript object containing the properties that were transmitted through AJAX.

That should allow you to handle it the way you appear to be trying to.

Looks like JSON.parse was added when ECMA5 was added, so anything fairly modern should be able to handle this natively... if you have to handle fossils, you could also try external libraries to handle this, such as jQuery or JSON2.

For the record, this was already answered by Andy E for someone else HERE.

edit - Saw the request for 'official or credible sources', and probably one of the coders that I find the most credible would be John Resig ~ ECMA5 JSON ~ i would have linked to the actual ECMA5 spec regarding native JSON support, but I would rather refer someone to a master like Resig than a dry specification.


I'm not sure whats going wrong with your set up. Maybe the server is not setting the headers properly. Not sure. As a long shot, you can try this

$.ajax({
    url : url,
    dataType : 'json'
})
.done(function(data, statusText, resObject) {
   var jsonData = resObject.responseJSON
})

parse and convert it to js object that's it.

success: function(response) {
    var content = "";
    var jsondata = JSON.parse(response);
    for (var x = 0; x < jsonData.length; x++) {
        content += jsondata[x].Id;
        content += "<br>";
        content += jsondata[x].Name;
        content += "<br>";
    }
    $("#ProductList").append(content);
}

It works fine, Ex :

$.ajax({
    url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "?????",
    type: 'GET',
    cache: false,
    success: function(result) {
        //  alert(jQuery.dataType);
        if (result) {
            //  var dd = JSON.parse(result);
            alert(result[0].Id)
        }

    },
    error: function() {
        alert("No");
    }
});

Finally, you need to use this statement ...

result[0].Whatever

One of the way you can ensure that this type of mistake (using string instead of json) doesn't happen is to see what gets printed in the alert. When you do

alert(data)

if data is a string, it will print everything that is contains. However if you print is json object. you will get the following response in the alert

[object Object]

If this the response then you can be sure that you can use this as an object (json in this case).

Thus, you need to convert your string into json first, before using it by doing this:

JSON.parse(data)