Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show loading dialog for multiple ajax request

I am making two ajax call asynchronously, on each call I am showing a loading dialog box like this,

jQuery('#msg_writter').show();

on success of each request I will hide the loading dialog like this,

jQuery('#msg_writter').fadeOut(1000);

my html code for loading dialog:

<div id="msg_writter" class="msgWritter">    
     <img src="/images/loading.gif"/>
</div>

when the first request is done, the loading dialog gets disappear so loading dialog is not showing for the second request.

How could I modify the code to show the loading dialog from the first request till the success of last request.

like image 409
Arivarasan L Avatar asked Sep 05 '25 03:09

Arivarasan L


1 Answers

You must count AJAX request counts:

var activeAjaxCount = 0;

// When making request, increment count and show loader
activeAjaxCount++;
jQuery('#msg_writter').show();

// On complete callback, decrease count and fadeout loader if count is zero
activeAjaxCount--;
if (activeAjaxCount == 0) {
    jQuery('#msg_writter').fadeOut(1000);
}

You can also use $.ajaxStart and $.ajaxComplete to solve that globally.

var activeAjaxCount = 0;

$( document ).ajaxStart(function() {
    activeAjaxCount++;
    $('#msg_writter').show();
});

$( document ).ajaxComplete(function() {
    activeAjaxCount--;
    if (activeAjaxCount == 0) {
        jQuery('#msg_writter').fadeOut(1000);
    }
});
like image 96
Murat Çorlu Avatar answered Sep 07 '25 20:09

Murat Çorlu