20

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?

LordZardeck
  • 7,953
  • 19
  • 62
  • 119

3 Answers3

32

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
    }
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
6

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');
});
SeanWM
  • 16,789
  • 7
  • 51
  • 83
2

Try using jQuery's ajaxStart event

epascarello
  • 204,599
  • 20
  • 195
  • 236
  • 1
    I would probably use `ajaxSend` instead as it is triggered for all the ajax requests (vs only the 1st one with `ajaxStart`). see also http://stackoverflow.com/questions/3735877/whats-the-difference-between-1-ajaxstart-and-ajaxsend-and-2-ajaxstop-and – Adriano Sep 11 '14 at 08:29
  • Another note: @LordZardeck might want to remove the "loading..." progress bar when all the ajax requests either finish successfully or with errors. That's something to be done using `.ajaxError()` and `.ajaxStop()` – Adriano Sep 11 '14 at 08:34