How do I add a spinner to my AJAX application?

I have an AJAX application using Prototype which pulls data from a server. How can I show one of those spinning AJAX-style circles while data is loading?


This was actually a question I had while working on WPAuctions, a plugin that lets you auctions stuff right off your WordPress blog. I had a couple of AJAX calls that populate the lightbox with auction and bid data, and I wanted to add some sort of indication to the user that something was happening in the background.

Finding the answer on the Web was a bit hairy, but the mechanism is really straight-forward. And I do have JarosÅ‚aw DobrzaÅ„ski to thank for the solution. It’s a 2-step solution that is so simple to implement, it’s almost painful. Here’s what you do:

1. Add this code to the header of your website (not forgetting to include prototype.js of course):
Ajax.Responders.register({
onCreate
: function(){ Element.show('spinner')},
onComplete
: function(){Element.hide('spinner')}
});

2. Add this tag where you would like the spinner image to appear:
<img alt="spinner" id="spinner" src="gfx/spinner.gif" style="display:none;" />

And you’re done! The code in the header registers a responder with the AJAX library that shows and hides the spinner image when an AJAX call is created and completed respectively. You can use the following indicators if you wish:

Spinner 1 : Spinner 1
Spinner 2 : Spinner 2

The spinners above are pretty generic, so you can use them whether you’re creating a site about web hosting, Chevy Tahoe accessories, shopping or a search directory.

Alternatively you can create your a custom spinner here.

2 thoughts on “How do I add a spinner to my AJAX application?”

  1. You know, I have to tell you, I really do enjoy this blog and all the insightful comments everyone has. It really helps me polish my own thoughts on a lot of these subjects, so thanks to all who participate, I for one appreciate it a lot.

    Best regards!

Leave a Reply

Your email address will not be published. Required fields are marked *