Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute function after all ajax .load() requests are finished

Tags:

jquery

ajax

I have a page that has a tab set. Each of the tabs is loaded by the jQuery .load() function.

I want to display a loading animation that disappears when all of the ajax requests are finished. However, document.ready() has only provided me with limited success.

How can I ensure that all ajax requests are completed before executing the code to hide the loading animation?

like image 781
Mike Avatar asked Mar 23 '10 19:03

Mike


People also ask

How do you check if all AJAX calls are completed?

The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.

How would fire a callback when any AJAX request on a page has completed?

The ajaxComplete() method specifies a function to be run when an AJAX request completes. Note: As of jQuery version 1.8, this method should only be attached to document. Unlike ajaxSuccess(), functions specified with the ajaxComplete() method will run when the request is completed, even it is not successful.

Can we execute run multiple AJAX request simultaneously in jQuery?

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.


4 Answers

.ajaxStop(handler)

Documentation here: http://api.jquery.com/ajaxStop/

like image 87
JC Ford Avatar answered Oct 13 '22 00:10

JC Ford


$(document).ready(function () {
     $(document).ajaxComplete(function () {
         alert('Completed');
     });
});
like image 31
Zubair sadiq Avatar answered Oct 12 '22 23:10

Zubair sadiq


ajaxComplete

Per the documentation:

$('.log').ajaxComplete(function() {
    $(this).text('Triggered ajaxComplete handler.');
});
like image 45
Jason Avatar answered Oct 12 '22 23:10

Jason


Use the callback argument to .load(), setting a flag or increasing a counter in the callback function. Once all flags are set or the counter reaches the number of tabs, you know all tabs have been loaded, and you can remove the animation.

In pseudocode that might or might not be valid JavaScript:

loadedTabs = 0;

function onLoad() {
    for (int i = 0; i < numTabs; ++i) {
        tabs[i].load(tabUrl(i), tabLoaded);
    }
}

function tabLoaded() {
    ++loadedTabs;
    if (loadedTabs == numTabs)
        loadingAnimation.display = 'none';
}
like image 27
Thomas Avatar answered Oct 13 '22 01:10

Thomas