0

I have data that php returned to JS but i dunno how to loop it to access the information... i have this:

    result = call_data('get_chat.php');
            console.log(result);
    for(var data in result){

        alert(result[data]["id"]); //says undefined

    }

Console Log shows:

   [{"eventtime":"0000-00-00 00:00:00","message":"test2","bywho":"dave","id":"2"},
    {"eventtime":"0000-00-00 00:00:00","message":"testttt","bywho":"dave","id":"1"}]  

So i want to loop each data from it but how do i do it im really confused!! It just says undefined each time.

Sir
  • 8,135
  • 17
  • 83
  • 146

2 Answers2

5

If typeof result === "string", then you still need to parse the response before you can iterate over it:

result = JSON.parse(call_data('get_chat.php'));

Then, as others have pointed out, you should use a simple for loop with Arrays:

for (var i = 0, l = result.length; i < l; i++) {
    console.log(result[i]["id"]);
}

for..in loops will iterate all enumerable keys rather than just indexes.

Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
2

It looks like your php code returns an array of objects, so you need to first iterate through the array, and then access the id key like so:

for (var i = 0; i < result.length; i++){
  var obj = result[i];
  console.log(obj.id); // this will be the id that you want
  console.log(obj["id"]); // this will also be the id  
}
user730569
  • 3,940
  • 9
  • 42
  • 68
  • result.length = 166 how ever... (typeof) for result is "string" =/ – Sir Sep 04 '12 at 01:48
  • @Dave That's because as Jonathon pointed out, it's a json string so calling `length` on it will return the number of characters in the string. Pass it to `JSON.parse` first. – user730569 Sep 04 '12 at 01:52