steveosoule
6/25/2014 - 9:09 PM

Dynamic Number of AJAX Calls $when().done()

Dynamic Number of AJAX Calls $when().done()

// FROM: http://stackoverflow.com/questions/14352139/multiple-ajax-calls-from-array-and-handle-callback-when-completed
// FROM: http://jsfiddle.net/MBZEu/4/
var list = ['obj1', 'obj2', 'obj3', 'obj4', 'obj5'];
var callback = function() {
  console.log("done");
};
var requests = [];

  for(i = 0; i < list.length; i++) {
    requests.push($.ajax({
      url: 'url',
      success: function() {
        console.log('suc');
      }
    }));
  }

$.when.apply(undefined, requests).then(function(results){callback()});

// Miva Example:
var requests = [];

multiAdd.$forms.each(function(){
	var $form = $(this);
	requests.push(
		$.ajax({
			url: $form.attr('action'),
			method: $form.attr('method'),
			data: $form.serialize() + '&registy=Add to Wishlist',
			cache: false,
			success: function(){
				console.log('success');
			}
		})
	);
});

$.when.apply(undefined, requests).then(function(results){
	console.log('then: ', results);
}).done(function(results){
	console.log('done: ', results);
	window.location = 'http://' + window.location.host + '/cs/MYREG';
});