Skip to content Skip to sidebar Skip to footer

Showing A Spinner During An Ajax Request?

what is the best way to show a spinner? I have prepared a div(id='spinner'), that should be visible during loading.

Solution 1:

Do you use jQuery?

If so you can use:

ajaxStart & ajaxStop: http://docs.jquery.com/Ajax

For example:

$(function(){

    // hide it first
    $("#spinner").hide();

    // when an ajax request starts, show spinner
    $.ajaxStart(function(){
        $("#spinner").show();
    });

    // when an ajax request complets, hide spinner    
    $.ajaxStop(function(){
        $("#spinner").hide();
    });
});

You can fine tune a little with a request counter that increments and decrements in case you have a lot of simultaneous requests.

If you don't use jQuery, check out the jQuery Source code for which events ajaxStart actually register in plain old javascript.

HTH Alex

Solution 2:

I used this in my rails app. This worked for me:

$(document).ajaxSend(function(r, s) {
$("#spinner").show();});


$(document).ajaxStop(function(r, s) {
$("#spinner").fadeOut("fast");});

Solution 3:

$().ajaxSend(function(r, s) {
    $("#spinner").show();
});

$().ajaxStop(function(r, s) {
    $("#spinner").fadeOut("fast");
});

Post a Comment for "Showing A Spinner During An Ajax Request?"