gurehbgui gurehbgui - 7 months ago 28
Javascript Question

Show a loading bar using jQuery while making a AJAX request

I'm making a AJAX request with jquery like:

$.get('/Stuff.php', function (data) {
$('#own').html(data);
});


while this data is loading I want to display a small text at the top of the page (which just says "loading...") without blocking it.

how to do this?

grr grr
Answer

3nigma is on the right track, but got one detail wrong, at least in the general case.

Using ajaxSetup only provides defaults, if later you make some ajax calls that specify their own callbacks for beforeSend (i.e. you need to set some specific headers) or complete (you want to handle both success and error the same) they will override the ones in ajaxSetup and your loading indicator will break.

Instead, use Global Ajax Events (more about ajax events)

$(document).ajaxSend(function(e, jqXHR){
  //show the loading div here
});
$(document).ajaxComplete(function(e, jqXHR){
  //remove the div here
});

This is a more generic solution that will not break even if other code also wants so set some global or local beforeSend/complete handlers or calls ajaxSetup.