For specific AJAX call:
$.ajax({..., beforeSend: function(){ /* show the loading thing */ },
complete: function(){ /* hide the loader */ }});
General:
jQuery.ajaxSetup({
beforeSend: function() {
$('#loader').show();
},
complete: function(){
$('#loader').hide();
},
success: function() {}
});
My personal best jQuery “Please Wait, Loading…” animation?:
// a bit modified for jQuery 1.8 and error handling (CSS and instruction at the link)
$(document).on(
{
ajaxStart : function()
{
if (!$('div.modal').length)
{
$('body').append($('<div>',
{
'class' : 'modal'
}));
}
$('body').addClass("loading");
},
ajaxStop : function()
{
$('body').removeClass("loading");
},
ajaxError : function(e, x, settings, exception)
{
var message, statusErrorMap =
{
'400' : "Server understood the request but request content was invalid.",
'401' : "Unauthorised access.",
'403' : "Forbidden resouce can't be accessed",
'500' : "Internal Server Error.",
'503' : "Service Unavailable."
};
if (x.status)
{
message = statusErrorMap[x.status];
if (!message)
{
message = "Unknow Error.";
}
} else if (e == 'parsererror')
{
message = "Error.\nParsing JSON Request failed.";
} else if (e == 'timeout')
{
message = "Request Time out.";
} else if (e == 'abort')
{
message = "Request was aborted by the server";
} else
{
message = "Unknow Error.";
}
alert(message);
}
});