Terry Terry - 1 month ago 18
jQuery Question

Ajax success function returning [object, object]

I'm very new to AJAX calls - poked around the web for a few tutorials but still not quite getting successful at it.

The input field has an assigned ID of "idkey". The script is as follow:

$(document).on("keyup.autocomplete", "#idkey", function(){
var query = "q=" + $(this).val();
$.ajax({
url: 'api.php',
type: 'GET',
data: query,
dataType: 'json',
success: function(data) {
alert(data);
for (var i=0;i<data.length;i++) {
content = data[i].IDKey;
content += "<br>";
$(content).appendTo("#output");
// updateListing(data[x]);
}
}
});
});


On the server side, the api.php has an output of:

[{"IDKey":"30000001"},{"IDKey":"30000002"},{"IDKey":"30000004"}]


I am not sure why the
alert(data)
would return
[object Object], [object Object], [object Object]
. Any clue to why this is happening?

p/s: The php file has a header set to
Content-Type: application/json
.

Answer

Your json response is an array of 3 objects . That's the reason you are seeing the alert as an object..

Try alert(data[0].IDKey) .. It should give you 30000001

To see the data try console.log or place the alert inside for loop

for (var i=0;i<data.length;i++) {
    alert(data[i].IDKey);
 }

$.each(data, function(i, value) {
   console.log('Value of '+ i +' is : ' + value);
})
Comments