Trigger A Function Only After The Completion Of Multiple Ajax Requests
Solution 1:
Update: Since jQuery 1.5, deferred objects provide a cleaner solution. Have a look at an example here.
I would use .ajaxComplete()
, it will be triggered whenever an Ajax call completed (success or error):
var numOfAjaxRequests = 5;
$(document).ajaxComplete(function() {
numOfAjaxRequests--;
if(!numOfAjaxRequests) {
doWork();
}
});
Then you don't have to edit every Ajax request.
You could even use .ajaxSend()
to get notified of starting Ajax requests, instead of hardcoding it (but I am not sure whether this really works, maybe you will experience race conditions):
var numOfAjaxRequests = 0;
$(document).ajaxSend(function() {
numOfAjaxRequests++;
});
Solution 2:
I think you should use complete(XMLHttpRequest, textStatus)
ajax event instead of success(data, textStatus, XMLHttpRequest).
According to jQuery help:
complete(XMLHttpRequest, textStatus)
A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The XMLHttpRequest object and a string describing the status of the request. This is an Ajax Event.
Solution 3:
I don't know enough about JavaScript internals, but there is a danger that the operation:
ajaxDoneCounter++;
is not atomic. If that is the case, then this could be subject to a race condition.
Post a Comment for "Trigger A Function Only After The Completion Of Multiple Ajax Requests"