How to find out if there is any Ajax request and ajax Success

I wonder how I can encode this

//if there is any ajax request $("#loader").css("display","block"); //on success: $("#loader").css("display","none"); 

Note: I am not going to enter the code again and again in every ajax request function. I want him. so my script knows if there is any ajax do $("#loader").css("display","block"); request $("#loader").css("display","block"); , and if there is any success ajax, $("#loader").css("display","none");

+7
source share
4 answers

The magic thing you're looking for is jQuery.ajaxStart () and jQuery.ajaxStop () , you can also find jQuery.ajaxComplete () .

Example:

 $("#loader").ajaxStart(function() { $(this).show(); }).ajaxStop(function() { $(this).hide(); }); 

You should use the hide() and show() methods instead of changing the CSS display attribute.

+8
source

Take a look at $.ajaxStart and $.ajaxEnd when you plug in your application in $ .document (done):

 $.ajaxStart(function(){ $("#loader").css("display", "block"); }) .ajaxStop(function(){ $("#loader").css("display", "none"); }); 

UPDATE forgot about ajaxStop ... @ The answer to Cory reminded me. Updated my answer.

+3
source

These other solutions are great, but I'm not sure if they are addressing your issue calling for CSS $("#loader") changes in startup and success .

Maybe something like this:

 $(document).ajaxStart(function() { // do something on start $("#loader").css("display","block"); }).ajaxError(function(e, xhr, settings) { // do something on error $("#loader").css("display","none"); }).ajaxSuccess(function() { // do something on success $("#loader").css("display","block"); }); 

Check out this correctly working example: http://jsbin.com/ocovoq/3/edit#preview

+2
source

If you start two or three ajax calls, ajaxStop will only start when the last is completed.

 var isMakingAjaxCall; $(document).ready(function () { // Loading Screen for Ajax Calls $("#loader").hide(); $("#loader").ajaxStart(function () { isMakingAjaxCall = true; RepositionLoading(); $("#loader").fadeIn(); }); $("#loader").ajaxStop(function () { $("#loader").fadeOut(); isMakingAjaxCall = false; }); }); function RepositionLoading() { $("#loader").css('left', "20px"); $("#loader").css('top', "20px"); }; 
+1
source

All Articles