I wonder how can I code this
//if there is any ajax request
$("#loader").css("display","block");
//on success:
$("#loader").css("display","none");
Note :
i am not going to code it again and again in my each ajax request function.
i want it Genric. so that my script knows if there is any ajax request do $("#loader").css("display","block");
and if there is any ajax success do $("#loader").css("display","none");
AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.
success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine. However, . complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - . complete() will still get called.
By default, the JavaScript Agent limits the Ajax requests (using XHR or the Fetch API) sent for base or virtual pages. The limit is 250 requests for single-page applications (SPAs) and 50 for non-SPAs.
The magical thing you are looking for is jQuery.ajaxStart() and jQuery.ajaxStop(). You might also find jQuery.ajaxComplete() useful.
Example:
$("#loader").ajaxStart(function() {
$(this).show();
}).ajaxStop(function() {
$(this).hide();
});
You should use the hide()
and show()
methods instead of changing the display
CSS attribute.
Take a look at $.ajaxStart
and $.ajaxEnd
when you wire up your app in $.document(ready):
$.ajaxStart(function(){
$("#loader").css("display", "block");
})
.ajaxStop(function(){
$("#loader").css("display", "none");
});
UPDATE forgot about ajaxStop...@Cory's answer reminded me. Updated my answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With