tags:

views:

68

answers:

3

One of my pages has about 5 jQuery AJAX calls that fire off as soon as the page loads. I know that I can track each AJAX call individually and know when it is complete, but is there any way to track them as a whole? This way, I'll know when the last AJAX call is complete and I can signal a UI change.

I guess I could keep a running count of the number of "active" calls and check that number each time a call completes, but is there a more eloquent solution?

+5  A: 

Have a look at the global ajaxStart and ajaxStop events.

Here's how I've used them:

$('body')
    // Set up loading animation for requests.
    .ajaxStart(function () {
        $(this).addClass('loading');
    })
    .ajaxStop(function () {
        $(this).removeClass('loading');
    });
Blixt
Thanks Blixt, I appreciate it!
James Skidmore
A: 

You could use queue/dequeue which are useful for any function calls:

http://jqueryfordesigners.com/api-queue-dequeue/

You could put your UI function at the end of the queue.

Down side is that it causes your functions to be synchronous.

Nissan Fan
Thanks Nissan. It looks like that would work, but fortunately there's an easier way already built into jQuery :)
James Skidmore
Glad you got your answer.
Nissan Fan
A: 

The ajax object has a method especifically for this: complete() which is fired when the request finishes (after success and error callbacks are executed).

$.ajax({
    type: "POST",
    url: "some.php",
    data: "name=John&location=Boston",
    complete: function(){
        alert( "action finished" );
    }
});
Elzo Valugi