83

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.

actkatiemacias
  • 1,433
  • 2
  • 14
  • 16

12 Answers12

116

The data is coming back as the string representation of the JSON and you aren't converting it back to a JavaScript object. Set the dataType to just 'json' to have it converted automatically.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
  • 5
    @DipakYadav: `getJSON` won't POST. – Marcelo Cantos Jul 02 '13 at 09:06
  • 8
    @MarceloCantos (about your answer): This is true. However, according to [jQuery Manual](http://api.jquery.com/jQuery.ajax/), "_any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected_". So you can use `dataType: 'json'` only, if you're sure, that server will return poperly formatted JSON. If it only returns "_a string, that looks like JSON_", you should use `dataType: "text json"` to force jQuery conversion. – trejder Jul 02 '13 at 09:06
  • 1
    header('Content-Type: application/json'); if you are using php – Rob Sedgwick Apr 17 '16 at 16:14
82

I recommend you use:

var returnedData = JSON.parse(response);

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

d-_-b
  • 21,536
  • 40
  • 150
  • 256
abobreshov
  • 853
  • 6
  • 4
  • 2
    @RyanGates I believe, that abobreshov is talking about simple `success: function (data) {data = JSON.parse(data);}`, if I'm not mistaken. – trejder Jul 02 '13 at 08:54
11

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
Max Base
  • 639
  • 1
  • 7
  • 15
Amin Saadati
  • 719
  • 8
  • 21
10

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.

Community
  • 1
  • 1
Steve
  • 580
  • 7
  • 14
10

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)
aash
  • 1,323
  • 1
  • 14
  • 22
6

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);
});
octothorpentine
  • 319
  • 2
  • 18
arabeske
  • 79
  • 1
  • 2
4

you can use the jQuery parseJSON method:

var Data = $.parseJSON(response);
Community
  • 1
  • 1
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44
2

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);
            }
        });
    });
});
Max Base
  • 639
  • 1
  • 7
  • 15
1

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
})
pravin
  • 1,106
  • 1
  • 18
  • 27
0

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.

Sky Yip
  • 1,059
  • 12
  • 10
0

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);
}
Max Base
  • 639
  • 1
  • 7
  • 15
0

Use dataType: 'json'

In .NET you could also return Json(yourModel) in your action method/API controller.

And parse the returned JSON as follows in the Jquery .ajax:

if you've a complex object: navigate to it directly.

success: function (res) { 
$.each(res.YourObject, function (index, element) {                                
  console.log(element.text);
  console.log(element.value);
   });

 });