tags:

views:

38002

answers:

6

In Prototype I can show a "loading..." image with this code:


var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, 
onLoading: showLoad, onComplete: showResponse} );

function showLoad () {
    ...
}

In jQuery, I can load a server page into an element with this:

$('#message').load('index.php?pg=ajaxFlashcard');

but how do I attach a loading spinner to this command as I did in Prototype?

+51  A: 

there's a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself.

$('#loadingDiv')
    .hide()  // hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })
;

The ajaxStart/Stop functions will fire whenever you do any ajax calls.

nickf
That's probably too global for one simple load into a DIV.
dalbaeb
too global? how many different "please wait" messages do you want?
nickf
Perfect! nice and clean
Derek
Exactly what I needed. Thanks.
friederbluemle
this way unfortunately you can't control loading div positioning in case you don't want to just show a modal loading window, but show it near the element waiting for ajax content to be loaded in...
glaz666
+11  A: 
UltimateBrent
+4  A: 

You can insert the animated image into the DOM right before the AJAX call, and do an inline function to remove it...

$("#myDiv").html('<img src="images/spinner.gif" alt="Wait" />');
$('#message').load('index.php?pg=ajaxFlashcard', null, function() {
  $("#myDiv").html('');
});

This will make sure your animation starts at the same frame on subsequent requests (if that matters). Note that old versions of IE might have difficulties with the animation.

Good luck!

Josh Stodola
wow thanks this realy worked for me
streetparade
Top tip: Preload the spinner.gif in a div with display set to none. Otherwise you might get a bit of a delayed spinner effect as the spinner still downloads.
uriDium
A: 

JS --

$.listen('click', '#captcha', function() {
    $('#captcha-block').html('<div id="loading" style="width: 70px; height: 40px; display: inline-block;" />');
    $.get("/captcha/new", null, function(data) {
        $('#captcha-block').html(data);
    }); 
    return false;
});

CSS --

#loading { background: url(/image/loading.gif) no-repeat center; }
+4  A: 

Use the loading plugin: http://plugins.jquery.com/project/loading

$.loading.onAjax({img:'loading.gif'});

Nathan Bubna
+4  A: 

For jQuery I use

jQuery.ajaxSetup({
  beforeSend: function() {
     $('#loader').show()
  },
  complete: function(){
     $('#loader').hide()
  },
  success: function() {}
});
kr00lix