views:

68

answers:

3

I have simple AJAX function that uses jQuery to return an array of 300 test objects from a database. I can see the data is returned, and I can use FireBug to step through the first loop and step into the constructor.

This data is copied to an JS array. The code fragment looks like:

    //retrieve star locations to display on page
    $.getJSON("stars.php?jsoncallback=?", function(data) {
     for (var x=0, xx=data.length; x<xx; x++) {
//    planetArray[x] = new Planet(data[x].xpos, data[x].ypos); // also doesn't work.
      planetArray.push(new Planet(data[x].xpos, data[x].ypos));
     }
    });

    for (var i=0, ii=planetArray.length; i<ii; i++) {
     // display the data.
    }

FireBug says planetArray.length is zero. The Planet constructor looks like:

function Planet(x, y) {
    this.x = x;
    this.y = y;
}

I think it is a scoping issue but I can't seem to figure it out. In other languages creating a new object means it exists on the heap and survives the scope, but here it seems to disappear into the ether.

How can I return an array and push it into my own array for use later (or even in another function)?

+1  A: 

It should help if you add planetArray = []; before the example code.

Hugo
That was left out for brevity. Actually I used `var planetArray = new Array();` but it is all the same.
graham.reeds
+5  A: 

The AJAX request happens asynchronously - you're not waiting for it to complete before you try and display the data.

Move the display code into the callback and it should work.

Greg
But what if I want to use that array elsewhere in my code? How can I guarentee that the data has loaded? A low-tech way would be to check that 'planetArray.length > 0' but even that might have problems.
graham.reeds
Well if it's onload actions then you should place everything in the Ajax callback. Otherwise create bool/timestamp variable keeping load status.
Tomasz Durka
+1  A: 

Actually just mergin both answers.
Like Greg said it works asynchronously meaning when second part (// display the data loop) is executed, the request didn't come back yet, so array is not filled.

var planetArray = [];
//retrieve star locations to display on page
$.getJSON("stars.php?jsoncallback=?", function(data) {
  for (var x = 0; x < data.length; x++) {
    planetArray.push(new Planet(data[x].xpos, data[x].ypos));
  }
  for (var i = 0; i < planetArray.length; i++) {
    // exectutes after part below
    // data already filled
  }
});

for (var i = 0; i < planetArray.length; i++) {
  // NO DATA YET
}
Tomasz Durka