How can I know the number of active ajax requests using jQuery?
I understood that it jQuery.active
gave that value, but it is not working.
At one point in an app, I fire a custom event with jQuery:
$('body').trigger('association:change');
Several processes are waiting for this event, and each one performs an ajax request on its own, which can result in several simultaneous requests. To indicate to the user that the system is carrying out operations, I show an animation of the "loading" type. When the last of the requests finishes, you should hide this animation. Until now, I believed that with
if ($.active < 1) {
$('.loading').hide();
}
could get it. Is there any way to know the number of unfinished ajax requests with jQuery?
To do the task you want you have available
ajaxStop()
:Also including the start of the load, the code would look something like this:
I have been investigating in the jQuery code the use of
jQuery.active
and it should report the number of connections that are unfinished, but it depends on the place and/or moment in which you access that property , it will contain what you expect or not since its value is decremented at the end of the eventdone
, so if you try to access that value during the execution of acallback
dedone
you will not have the updated value (for example).By the way, to keep accounts, make sure all AJAX requests are attached to
document
:Edit: I have developed a proof of concept in which you can check that my proposal works correctly:
You can also see what I said. During the execution of the event
success/done
the counter has not yet been decremented, so the last one will see a value of$.active
1, instead of 0, even within the.when()
final block.You could do the following:
association:change
, using the.on()
subscribe to events methodajaxStart
andajaxStop
ajaxStop
it fires, you use.off()
to unsubscribe.For example:
PD1 : If
$.ajax()
o$.ajaxSetup()
is called with the optionglobal: false
, eventsajaxStart
andajaxStop
will not be fired.PD2 : Since you use events to trigger actions, you could create a new event (eg:
loader:ajax
), to automatically display theloader
.Finally I have solved it in another way, although the option of the ajaxStart/ajaxStop events is also quite interesting.
Using the jQuery.when().then(); I can reach the same end that I was looking for, and for my taste, in a much cleaner way than I tried before.
It is not the solution that we were looking for at first, but it adapts quite well to the expected result.