Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple ajax calls from array and handle callback when completed

Tags:

I have used promises in jQuery slightly before - but I am having trouble applying it to this scenario. I prefer to use the $.when() and $.done() methods to achieve this.

From what I understand I need to build a $.Deferred object which logs the requests and when those requests are finished - fire the callback. In my code below the callback is firing before the ajax requests and not after - maybe I just need some sleep

I know my code is incomplete I have been struggling to apply it with the addition of the for loop.

http://jsfiddle.net/whiteb0x/MBZEu/

var list = ['obj1', 'obj2', 'obj3', 'obj4', 'obj5']; var callback = function() {   alert("done"); }; var requests = [];  var ajaxFunction = function(obj, successCallback, errorCallback) {   for(i = 0; i < list.length; i++) {     $.ajax({       url: 'url',       success: function() {             requests.push(this);       }     });   } }; $.when($.ajax(), ajaxFunction).then(function(results){callback()}); 
like image 713
user1982408 Avatar asked Jan 16 '13 05:01

user1982408


People also ask

How do I handle multiple AJAX requests?

The jQuery library provides a way to make any callback function waiting for multiple Ajax calls. This method is based on an object called Deferred. A Deferred object can register callback functions based on whether the Deferrred object is resolved or rejected. Here is an example of the Deferred object.

How do I stop multiple AJAX calls from repeated clicks?

click(function(e) { e. preventDefault(); if ( $(this). data('requestRunning') ) { return; } $(this). data('requestRunning', true); $.

Can we call two AJAX inside AJAX?

There is a requirement to make multiple AJAX calls parallelly to fetch the required data and each successive call depends on the data fetched in its prior call. Since AJAX is asynchronous, one cannot control the order of the calls to be executed.


1 Answers

The arguments to $.when should be the return value of $.ajax, which also doesn't need to be called separately -- that makes no sense. You want something like this:

for (i = 0; i < list.length; i++) {    requests.push($.ajax(...)); } $.when.apply(undefined, requests).then(...) 

The reason that .apply is needed is because $.when can take multiple arguments, but not an array of arguments. .apply expands essentially to:

$.when(requests[0], requests[1], ...) 

This also assumes that the requests can be completed in any order.

http://jsfiddle.net/MBZEu/4/ -- notice that 'done' is logged to the console after all of the success messages.

like image 198
Explosion Pills Avatar answered Oct 05 '22 15:10

Explosion Pills