How do I properly start the counter until the AJAX request completes?
I need to show a counter with a message while a given AJAX request is in progress and should stay there until the call is complete. I don't care about the return status from the call, as I will handle it later (in the same code), so 404, 500, 200, or any other status is valid.
I currently understand this:
$(document).bind("ajaxSend", function () {
load_start('Please wait, we are processing data...');
}).bind("ajaxComplete", function () {
load_end();
});
In the above case, for some reason (perhaps because the explanation here about the difference between ajaxComplete
vs ajaxStop
- the value ajaxComplete
means the AJAX call was successfully started) stop the counter until the call completes, because I see it only works in the Chrome developer toolbar ...
The user then tries to click the same button again because they don't see anything on the page and they won't go to the Dev dashboard to see if the AJAX call is still in progress or not.
I did this just as long ago:
$.ajax({
...
}).beforeSend(function () {
load_start('Please wait, we are processing data...');
}).always(function(){
load_end();
});
But I am facing the same problems. What would be the correct way to handle this? If there is any plugin out there and I need to recommend it.
source to share
If you want to do this for multiple AJAX requests without having to write loading code in every request. You can do something like 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
});
source to share
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 the request completes
$('#button').on('click', function() {
load_start('Please wait, we are processing data...');
$.ajax({
....
error: handleCallback,
success: handleCallback
});
});
function handleCallback(response, status, jqxhr) {
...
load_end();
}
source to share