Thursday, June 20, 2013

Jquery ajax start and ajax stop in pages having multiple ajax/asynchronous calls

your page is having multiple ajax calls, had problems in showing spinner/loader/some html duirng those requests are getting processed..?

here is a simple solution use jquery ajaxStart and ajaxStop options as below

$(document).ajaxStart(
   //show some loader/spinner
);

$(document).ajaxStop(
   //hide some loader/spinner
);

that's it....

hmm wait a second i had seen a problem with above process. My page has multiple ajax calls which were called at a time and my spinner is getting hidden on the completion of first request(it's working as perfect as it should).

to over come this behaviour i just took the help of a javascript variable and modified above mentioned script as follows.

var counter = 0;

$(document).ajaxStart(
   counter++;
   if(spinner is not visible)
    //show some loader/spinner
);

$(document).ajaxStop(
    counter--;
    if(spinner is visible and counter == 0)
     //hide some loader/spinner
);

the variable counter gets incremented for every request in ajaxStart and decrements on completion of each request in ajaxStop and we will hide the spinner only when counter becomes 0 i.e., at the end of final request.

that's it.

Feel free to comment.

Happy jQuery