zabware zabware - 10 days ago 7
CSS Question

Show loading image while $.ajax is performed

I am just wondering how to show an image that indicates that the async request is running. I use the following code to perform a async request:

$.ajax({
url: uri,
cache: false,
success: function(html){
$('.info').append(html);
}
});


Any ideas?

Answer

You can, of course, show it before making the request, and hide it after it completes:

$('#loading-image').show();
$.ajax({
      url: uri,
      cache: false,
      success: function(html){
        $('.info').append(html);
      },
      complete: function(){
        $('#loading-image').hide();
      }
    });

I usually prefer the more general solution of binding it to the global ajaxStart and ajaxStop events, that way it shows up for all ajax events:

$('#loading-image').bind('ajaxStart', function(){
    $(this).show();
}).bind('ajaxStop', function(){
    $(this).hide();
});