Reputation: 5494
I built an Ajax request with jQuery where - at the end of the PHP file, which is called - an array is the result:
echo json_encode(array('status' => 'true'));
Within my jQuery in the calling file, I would like to read if the status
is true
and I tried it with this:
$.ajax({
type: "GET",
url: "logic.php",
data: "receiver=" + receiverIds + "&subject=" + subject + "&msg=" + msg,
success: function(data){
$.each(data, function (i, elem) {
alert(elem.status);
});
}
});
but the alert is always undefined
. When I insert this line before the $.each
:
$("#additionalTextDiv").html(data);
I get the following result: {"status":"true"}
But why is the each function not working properly?
Thanks!
Upvotes: 1
Views: 1396
Reputation: 76003
Change the dataType
property of the options object you are setting in your AJAX call to json
so the JSON string gets parsed into a JavaScript object:
$.ajax({
type: "GET",
url: "logic.php",
dataType: 'json',
...
.ajax()
: http://api.jquery.com/jquery.ajax
Your $.each()
loop works just fine, here is a demo: http://jsfiddle.net/54pB9/
However if you are going to loop through a lot of records a for
loop will perform faster:
for (var i = 0, len = data.length; i < len; i++) {
alert(data[i].status);
}
Here is a demo: http://jsfiddle.net/54pB9/1/
Upvotes: 3