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?
Answer: Use the ajaxStart() and ajaxStop() Method You can create a preloader using the jQuery ajaxStart() and ajaxStop() method.
Step 1: Add a background with a spinner gif on top of the page, then remove them when everything is loaded. Step 2: Add a little script right after the opening body tag to start displaying the load/splash screen. Save this answer.
In not for only one ajax request, but if you want to load image on every ajax request then you can do that using bellow example. I use ajaxStart() and ajaxComplete() function for show image until All POST or GET Ajax request. this both function will execute one each $. ajax request.
There are 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.
Update: As of jQuery 1.8, the documentation states that .ajaxStart/Stop
should only be attached to document
. This would transform the above snippet to:
var $loading = $('#loadingDiv').hide(); $(document) .ajaxStart(function () { $loading.show(); }) .ajaxStop(function () { $loading.hide(); });
For jQuery I use
jQuery.ajaxSetup({ beforeSend: function() { $('#loader').show(); }, complete: function(){ $('#loader').hide(); }, success: function() {} });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With