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!
$.each,iwill be the property name andelemthe value, but you can also access it withobj.statusonce you parsed it.json_encode(array('status' => 'true'));does not translate to an array in JavaScript. It's more likely to end up in a JavaScript object that looks like this{status: "true"}, which you would NOT want to loop over.