Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON from JQuery.ajax success data

Tags:

json

jquery

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.

like image 548
actkatiemacias Avatar asked Mar 13 '11 11:03

actkatiemacias


People also ask

How JSON fetch data using Ajax?

Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.

How can I get specific data from Ajax response?

You can't as it's asynchronous. If you want to do anything with it, you need to do it in a callback. How? Because it's asynchronous, javascript will fire off the ajax request, then immediately move on to execute the next bit of code, and will probably do so before the ajax response has been received.

What does the JSON parse () method do when we initiate an Ajax request?

Description: Takes a well-formed JSON string and returns the resulting JavaScript value.

What is success response Ajax?

Response is the object passed as the first argument of all Ajax requests callbacks. This is a wrapper around the native xmlHttpRequest object. It normalizes cross-browser issues while adding support for JSON via the responseJSON and headerJSON properties.


2 Answers

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.

like image 104
Marcelo Cantos Avatar answered Sep 19 '22 23:09

Marcelo Cantos


I recommend you use:

var returnedData = JSON.parse(response); 

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

like image 45
abobreshov Avatar answered Sep 17 '22 23:09

abobreshov