Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catch all ajax requests in jquery

Tags:

I'm wanting to show a "Loading" progress bar every time an ajax request is sent. Is it possible to be notified ANYTIME an ajax request is sent using jQuery?

like image 229
LordZardeck Avatar asked Jan 28 '12 07:01

LordZardeck


People also ask

How do you check if all AJAX calls are completed?

The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.

How check Ajax request is successful jQuery?

$. ajax({ url: "page. php", data: stuff, success: function(response){ console. log("success"); } });

How do I get Ajax request?

send = function() { console. log( arguments ); //Here is where you can add any code to process the request. //If you want to pass the Ajax request object, pass the 'pointer' below var pointer = this var intervalId = window. setInterval(function(){ if(pointer. readyState !=

What is ajaxComplete in jQuery?

The ajaxComplete() method specifies a function to be run when an AJAX request completes. Note: As of jQuery version 1.8, this method should only be attached to document. Unlike ajaxSuccess(), functions specified with the ajaxComplete() method will run when the request is completed, even it is not successful.


2 Answers

You could use the $.ajaxSetup() method to set global AJAX properties that will apply for the entire page:

$.ajaxSetup({
    beforeSend: function() {
        // show progress spinner
    },
    complete: function() {
        // hide progress spinner
    }
});
like image 56
Darin Dimitrov Avatar answered Oct 22 '22 07:10

Darin Dimitrov


For some reason or another $.ajaxSetup() wasn't working for me. After reading through the docs though, I found the following:

Note: Global callback functions should be set with their respective global Ajax event handler methods—.ajaxStart(), .ajaxStop(), .ajaxComplete(), .ajaxError(), .ajaxSuccess(), .ajaxSend()—rather than within the options object for $.ajaxSetup().

Try $.ajaxStart() and $.ajaxComplete() instead:

$(document).ajaxStart(function () {
    console.log('Request Initiated');
});
$(document).ajaxComplete(function () {
    console.log('Request Complete');
});
like image 37
SeanWM Avatar answered Oct 22 '22 08:10

SeanWM