James Skidmore
James Skidmore

Reputation: 50288

Way to know when last AJAX call has completed in jQuery?

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?

Upvotes: 3

Views: 2900

Answers (3)

Elzo Valugi
Elzo Valugi

Reputation: 27856

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" );
    }
});

Upvotes: 0

Keith Adler
Keith Adler

Reputation: 21178

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.

Upvotes: 0

Blixt
Blixt

Reputation: 50169

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');
    });

Upvotes: 15

Related Questions