1

I am in a situation where I need to create a table using multiple AJAX Calls. I make an ajax request and get a JSON object with an array of elements (lets say 5). Run it through a for loop and at response of each ajax request create a row using parts of data from current looped element and current ajax call, then add it into a row to the table. (sorry for my bad grammar)

I would like to know how would I implement this using deferred objects? If my understanding is correct, this should be more simple to implement using deferred object? Correct?

My current implementation

$.ajax{
    //options
    success : function(data){

    // add col1, col2, col3 from first ajax call
        $(data).each(function(i,e){
            
            // make ajax request based on inputs from current loop element
            $.ajax({
                //options
                success: function(data) {
                    // add col5, col6 from first ajax call
                    // add col7, col8 from current loop element
                    // add <tr> to the table
                }
            });
            
        });
    
    }
}
Community
  • 1
  • 1
Atif
  • 10,623
  • 20
  • 63
  • 96

1 Answers1

2

Do you want to wait until all of your ajax calls have returned before updating the DOM? If you don't need to do this, then you can get by without using $.Deferred. Just update the DOM in each of your "success" callbacks.

If you DO want to wait until all calls have returned, then you could do something like this:

var promises = [];

$(data).each(function(i,e){

  // make ajax request based on inputs from current loop element
  promises.push($.ajax({ 
    // stuff 
  }));

});

$.when(promises).done(function() {
  // Update the DOM
});

I haven't tried this, so there could be a syntax error, but the idea is that an ajax call returns a "promise". This is essentially a promise that at some point in the future, it will have fulfilled its duties. So you push all of your promises into an array, then you can use the $.when function to execute some code when all promises are fulfilled.

Joel
  • 6,193
  • 6
  • 22
  • 22
  • exactly what I want, can you explain what is deferredInitializers as I don't see that initialized anywhere. – Atif Oct 30 '12 at 17:05
  • woops, copy paste error from some example code. that should have been "promises". I edited the example above. – Joel Oct 30 '12 at 18:27