Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly run a spinner until the AJAX request finish?

I need to show a spinner with a message while a given AJAX request is going on and should stay there until the call finish. I don't care at all about the return status from the call since I will handle it later on (at the same code) so 404, 500, 200 or any other status is a valid one.

Currently this is how I am handling it:

$(document).bind("ajaxSend", function () {
    load_start('Please wait, we are processing data...');
}).bind("ajaxComplete", function () {
    load_end();
});

In the case above, for some reason (maybe because what's explained here about the difference between ajaxComplete vs ajaxStop - meaning ajaxComplete means the AJAX call was started successfully) the spinner stop before the call is finished because I am seeing it just running at Chrome Developer Toolbar.

The user then is trying to click the same button again because is not seeing anything on the page and ofc they won't go to the Dev Toolbar to see if the AJAX call still being executed or not.

I did in this way time ago:

$.ajax({
    ...
}).beforeSend(function () {
    load_start('Please wait, we are processing data...');
}).always(function(){
    load_end();
});

But I run into the same issues. What would be the right way to handle this? If there is any plugin out there and I need it feel free to recommend it.

like image 428
ReynierPM Avatar asked Nov 01 '25 00:11

ReynierPM


1 Answers

If you want to do this for multiple AJAX requests without having to write the loading code in each request. You can do something as shown below.

 //This is called when the first AJAX request is fired.
    $(document).ajaxStart(function(event, jqXHR) {
        //Show spinner
    });

    //This is called after all the AJAX request are stopped.
    $(document).ajaxStop(function(event, jqXHR) {
        //Hide spinner

    });
like image 180
Rajesh P Avatar answered Nov 03 '25 13:11

Rajesh P