0

PHP json_encode as AJAX var "result":

[{"id":"139","assettypeid":"3","name":"skin1","body":"skin1.jpg"}]

I'm trying to access each property, but I can't:

for (var i =0;i < result.length-1;i++)
{
  var item = result[i];
  console.log (item.id + item.name + item.body);
}

All I see is:

NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
...

And there are way too many iterations ... as you can see in the JSON above, there should only be 4 loops.

3
  • 1
    What does console.log(result); show? And please add the code where you retrieve and parse the json encoded data! Commented Apr 26, 2012 at 21:04
  • [{"id":"139","assettypeid":"3","name":"skin1","body":"skin1.jpg"}] Commented Apr 26, 2012 at 21:43
  • Why do you subtract from the length? i < result.length - 1 should be for (var i=0; i < result.length; i++). Commented Apr 26, 2012 at 21:50

3 Answers 3

3

you need to use JSON.parse

var items = JSON.parse(result)

http://www.json.org/js.html

Sign up to request clarification or add additional context in comments.

Comments

1

UPDATE:

I modified my answer to create a JSON call to a server side file like PHP or Ruby. If you are using jQuery try this instead:

$.ajax({
    url: 'http://url-of-your-server-side.com/server-side-file-name.php',
    dataType: 'jsonp',
    jsonp: 'jsoncallback',
    success: function(data) {
        $.each(data, function(i,item){
            console.log (item.id + item.name + item.body);
        });
    error: function(){
        // execute upon failure
    }

Data is the variable that holds your array provided by your ajax request.

1 Comment

The reason for this is because you didn't parse your JSON before passsing it through the loop. In your example above, you did not add the part of your script that retrieve the JSON data and parses it. I modified my answer to add the jQuery version to parse and loop your server-side data.
0
for(var item in result){
    console.log(item.id, item.name, item.body);
}

1 Comment

you should not use such for in construction without checking if the result is an object or a prototype property

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.