0

I have something like this:

for(var i=0;i<deserializedData.forms.length;i++){
        $.ajax({
            type: "POST",
            url: "../getFormMetaData/",
            cache:false,
            data: {'a':'a'},
            success: getFormMetaDataCallback,
            error: displayAjaxError
        });
    }

Can i somehow do ajax calls when current is finished?

milandjukic88
  • 1,065
  • 3
  • 13
  • 30

2 Answers2

1

You could do something like this:

var ajax_index = 0; // which request we are currently processing
var arr = [ all, ajax, requests ]; // array of data for each request

// Execute a request
function doRequest( index ){
  $.ajax({
    type: "POST",
    data: arr[ index ]
    ...
    success: function(){
      // Once the request has responded, increase the index counter
      // and execute the next request
      ajax_index++;
      if ( ajax_index > arr.length ){
        // Continue executing requests if there are still remaining
        doRequest( ajax_index );
      }
    }
  });
}
doRequest( ajax_index );

By wrapping your AJAX request with a function, you can call this function multiple times each time with a different index in order to execute all of the requests sequentially.

Lix
  • 47,311
  • 12
  • 103
  • 131
1

Use the jQuery when function to wait for your promises.

http://api.jquery.com/jQuery.when/

A more detailed answer can be found here: Wait until all jQuery Ajax requests are done?

To use it with your loop, you have to save the deferred objects returns by jQuery.ajax in an array and pass that array to the jQuery.when function.

var deferredResults = [];
deserializedData.forms.forEach(function () {
    var deferredResult = $.ajax({
        ... // use no success or error callbacks here
    });
});
jQuery.when(deferredResults).done(function() {
    // if you don't know how many calls you made, use the function arguments.
    // this line turns the arguments objects into an array you can use safely.
    var results = Array.prototype.slice.apply(arguments)

});
Community
  • 1
  • 1
Tilman Schweitzer
  • 1,437
  • 10
  • 10