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.
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.
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.
Description: Takes a well-formed JSON string and returns the resulting JavaScript value.
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.
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.
I recommend you use:
var returnedData = JSON.parse(response);
to convert the JSON string (if it is just text) to a JavaScript object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With