Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing JSON data in a Javascript variable

It's embarrassing to have to ask, but I freely admit I'm an unseasoned Javascript developer, and I just can't figure this out. Hopefully, this will be dead simple for someone else, and I want to thank everyone here ahead of time for the help this site continually provides me.

A couple days ago, I asked this question, and am no longer getting that error. But I've run into a wall trying to actually access the data stored in the variable. My JSON looks like this:

[
    {"id":"1","name":"Bob","haircolor":"Brown"},
    {"id":"2","name":"Carol","haircolor":"Red"}
]

It's going into a variable like this:

var people=[];
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
    people.push(data);
});

Thanks to initializing people as an array, I no longer get any error messages. But I can't access the contents of people, either. people.length returns a 0, and people[0] and people[1] are undefined.

It's there, I know it's all there, but I'm having a devil of a time figuring out where.

like image 367
Damon Kaswell Avatar asked Nov 20 '25 19:11

Damon Kaswell


1 Answers

people only gets values after the ajax event happens.

Call some callback function after you put the data into the people array.

like image 187
Naftali Avatar answered Nov 23 '25 08:11

Naftali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!