4

I'm fairly new to javascript and jquery development. I have a table of values I'm fetching in PHP and formatting as a JSON string, because JSON looks like a great way to get data into javascript. But I'm having trouble addressing the javascript variable.

The JSON data is in a very simple format. It looks like this:

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

And so on. None of the entries are complex. It's just flat rows of data.

I'm using $.getJSON() from JQuery to place the data in a variable like so:

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

According to console.log(data), the object 'data' is getting populated with the contents of my JSON string. But the push is generating these errors in the javascript console:

Uncaught TypeError: Cannot read property 'length' of undefined
Uncaught TypeError: Cannot call method 'push' of undefined

What am I missing? And is there any other information you need to help me on this? I've ground to a halt on this project because of this problem, and I'm just too much of a javascript newbie to figure it out.

Damon Kaswell
  • 1,270
  • 1
  • 10
  • 16

5 Answers5

3

The variable people must be an array. Change the first line to

var people = [];

At the moment "people" is just undefined and the .push() method only works on arrays.

Didatus
  • 901
  • 1
  • 9
  • 14
  • That definitely got rid of the error, but for some reason, people.length is coming back zero. Shouldn't each entry be addressable with each array at people[0], people[1], and so on? Or am I misunderstanding the way .push() works? – Damon Kaswell Jan 27 '13 at 00:26
2

If your PHP writes the output like this:

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

You need to assign that whole structure to people:

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

// note that you can't access anything inside people here
// only when the json has been processed
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

Try defining your variable as an array before you push to it:

var people = new Array();
hohner
  • 11,498
  • 8
  • 49
  • 84
1

try initializing people variable as an array

var people = []
Can Geliş
  • 1,454
  • 2
  • 10
  • 19
1

You can try this:

$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
  $.each(data, function(i, people){
     console.log(people);
  });
});    
Jai
  • 74,255
  • 12
  • 74
  • 103