0

I'm a noob to JS/JQuery. Here's the code:

ids = ["1", "2", "3"]
var imageData = [];
for (i=0; i<ids.length; i++) {
    $.ajax({
        url: 'http://my.images.edu/' + ids[i] + '/info.json',
        type: 'GET',
        dataType: 'jsonp',
        success: function(data) {
            imageData.push(data);
        }
    });
};
// now I want to do stuff with in a loop with the populated 
// array, but it's always empty!
console.log(imageData.length);

The JSONP is working (I can log the JSON Object response to the console in the success function). My guess based on this question is that the array isn't populated yet when I want to use it, but I may be wrong. If that's the case, how do I get around it, and otherwise, what am I missing? Thanks in advance!

Community
  • 1
  • 1
JStroop
  • 475
  • 1
  • 8
  • 21

1 Answers1

0

imageData won't be edited until the current function context has completed its execution.

The code will run to completion and then the success callbacks will run one by one. You'll have to have your logic to handle the data placed inside the callbacks.

Since this looks like you actually want all the callbacks to complete before you do an operation, you probably want to look into jQuery deffereds

Something along these lines working in the loop.

$('#button').click(function() {
    $.when(
        $.ajax({
            url: '/echo/html/',
            success: function(data) {
                alert('request complete')
            }
        }),
        $.ajax({
            url: '/echo/html/',
            success: function(data) {
                alert('request complete')
            }
        })
    ).then( function(){
        alert('all complete');
    });
});
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
  • Hmm...this get me closer, so thanks for that. Two problems I think I'm still having: 1. the number of ajax calls in arbitrary (based on the number of ids) so somehow I'd like to have a loop in that `.when( ... )` method, and 2. in the success callback function I need to update a global array...so that `.then()` (or ideally outside the block altogether) I can do stuff with the array. – JStroop Mar 13 '13 at 02:37