Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if there is any Ajax Request and ajax Success

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");

like image 375
Fawad Ghafoor Avatar asked Mar 16 '12 16:03

Fawad Ghafoor


People also ask

What triggers AJAX success?

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.

What is difference between success and complete in AJAX?

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.

How many AJAX requests are there?

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.


2 Answers

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.

like image 193
Cᴏʀʏ Avatar answered Nov 10 '22 00:11

Cᴏʀʏ


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.

like image 44
David Hoerster Avatar answered Nov 10 '22 01:11

David Hoerster