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!
Change the
dataTypeproperty of the options object you are setting in your AJAX call tojsonso the JSON string gets parsed into a JavaScript object:.ajax(): http://api.jquery.com/jquery.ajaxYour
$.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
forloop will perform faster:Here is a demo: http://jsfiddle.net/54pB9/1/