Reputation: 18690
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.
Upvotes: 4
Views: 2152
Reputation:
Using always()
, despite the non-descriptive method naming, works if you want to wait for the ajax request to complete.
}).always(function () {
load_end();
});
Upvotes: 0
Reputation: 19184
update: using $.ajaxSetup
https://jsfiddle.net/ewwink/vmm7Lqz8/
$.ajaxSetup({
url: '/echo/html/',
beforeSend: load_start,
complete: load_end
});
you can do this, handleCallback
will be called after request finished
$('#button').on('click', function() {
load_start('Please wait, we are processing data...');
$.ajax({
....
error: handleCallback,
success: handleCallback
});
});
function handleCallback(response, status, jqxhr) {
...
load_end();
}
Upvotes: 3
Reputation: 363
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
});
Upvotes: 4