I am using json to read records. It works perfectly fine if I use it inside the javascript like this
var events=[{eventId:"1", event_name:"wedding"},{eventId:"2", event_name:"interview"}]
then loop it to read records
for(var events_count=0;events_count<events.length;events_count++)
{
//read records and works perfectly fine
}
but when I am doing the same using ajax, it is not working. I have even put the text
{eventId:"1", event_name:"wedding"},{eventId:"2", event_name:"interview"}
in the ajax called(ajax-get-events.php) page, It doesn’t go inside the loop
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//got data in same format as above in xmlhttp.responseText and used eval to parse it
events = eval('(' + xmlhttp.responseText + ')');
//I have tried to alert(events) and it shows [object object]
for(var events_count=0;events_count<events.length;events_count++)
{
//loop doesn't work at all
}
}
}
xmlhttp.open("GET","ajax-get-events.php",true);
xmlhttp.send();
Please tell me what I am missing.
Thanks
This is not parsed as a JSON array, but as one object (the second one):
But this should be parsed (read eval’d) as a correct array:
Since you’re using PHP, use
json_encodeto generate your JSON output, it’ll be correct JSON.