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.
Solution 1:
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.
Solution 2:
I recommend you use:
var returnedData = JSON.parse(response);
to convert the JSON string (if it is just text) to a JavaScript object.