Ok, so that title probably doesn't explain my question well. Hopefully this makes sense. This is also my first application with jQuery, so forgive me if I'm doing something dumb.
I have the following function:
function getRandomImages(limit) {
imagesArray = new Array();
$.getJSON('createImageArray.php', {limit: limit}, function(data) {
$.each(data, function(i) {
imagesArray[i] = data[i]; //imagesArray is declared globally.
});
});
}
The getJSON is correctly grabbing the JSON object. It returns something like this:
{"image0":"images/19.10.FBB9.jpg","image1":"images/8.16.94070.jpg","image2":"images/8.14.47683.jpg","image3":"images/8.15.99404.jpg","image4":"images/8.13.20680.jpg","image5":"images/21.12.9A.jpg","image6":"images/8.17.75303.jpg"}
I was debugging and am confident that data[i] correctly contains the image path as grabbed from the JSON object. However, after getRandomImages() is called, I look at my global imagesArray and notice that nothing has been changed. I'm guessing it's creating a copy of the imagesArray instead of grabbing the actual one.
Can someone tell me what I need to do so that my global imagesArray gets updated in the $.each block? Do I need to pass in imagesArray by reference somehow? Sorry, I'm a bit lost.
Thanks for the help.
EDIT: Some background information. I am populating an array of random image locations from the DB. I don't want to load all the images from the db to an array at once, because there are just too many. So, I have a counter which keeps track of where I am in my image array. Once I'm done with an image, I move the pointer to the next image. If I reach the end, I need to grab more random images. That's where the above js function gets called; it calls createImageArray.php which grabs x random images from the db and returns an array. I then want to store those image locations in my global imagesArray.
I'm not sure how I would restructure my code to take .getJSON's asynchronouos nature into account.