Reputation: 542
I'm trying to add a very simple loading GIF
in my AJAX. I use this animated gif.But, the GIF only moves for 0,5-1s only. Then, 10 sec later the data form AJAX is displayed.
$('#btn_src').on('click', function (e) {
$('.loading').show();
$.ajax({
type: "POST",
url: "some_function",
async: true,
cache: false,
dataType: "json",
data: 'some_var',
success: function (data) {
//some data from AJAX success call.
},
complete: function () {
$('.loading').hide();
$('#myModal').modal('show'); //This is a modal to display the data from AJAX
}
});
});
The current AJAX have this behavior:
What I expected is:
Upvotes: 4
Views: 972
Reputation: 1119
use this :
$(document).ajaxStart(function () {
$('.loading').show()
}).ajaxError(function (e, xhr, opts) {
$('.loading').hide();
}).ajaxComplete(function (e, xhr, opts) {
$('.loading').hide();
}).ajaxStop(function () {
$('.loading').hide();
});
or
use beforeSend in ajax :
$('#btn_src').on('click', function (e) {
$.ajax({
type: "POST",
url: "some_function",
async: true,
cache: false,
dataType: "json",
data: 'some_var',
beforeSend: function (msg) {
$('.loading').show();
}
success: function (data) {
//some data from AJAX success call.
},
complete: function () {
$('.loading').hide();
$('#myModal').modal('show'); //This is a modal to display the data from AJAX
}
});
});
Upvotes: 1
Reputation: 76464
The problem seems to be that the browser cannot make the spinner spin while working on your data. First you will need to test with commenting out the whole content of success
. If the spinner will not freeze then, that means that not the sheer size of data is the cause of this ui glitch, but the parsing. In this case you might want to modify your plan to divide the parsing job into chunks and call them bit by bit with little times between to allow the browser to handle the ui using setInterval
, but don't forget to call clearInterval
when the job is done. If the problem is with the sheer size of data, then you will either have to accept this behavior or to divide the responses into packets and send requests using setInterval
until there are no more packets to receive.
Upvotes: 1