Ads 468x60px

Labels

Wednesday, May 2, 2012

Showing progress

When doing AJAX requests, you may want to show some sort of progress while waiting for the request to finish, especially if it might take a while for it to do so. It's actually very simple to do so with jQuery, as you will see from the following example:



Right before performing the AJAX request, we change the text of the sender (the button which calls the function). As soon as it succeeds, we set it back. That's the simplest form of progress. Another approach is to show a piece of text somewhere on the page, but the most common way of doing it is to show a little piece of graphic which illustrates that the browser is currently working. You could make one yourself, or even better: Use one of the great online generators, for instance http://ajaxload.info/. I've created one, as you can see in the next example:



The process is pretty much the same, but instead of setting a text, we show and hide an existing image. You can place the image in a spot that the user is most likely to notice or dynamically place the image next to button/link clicked, if you have more than one. The possibilities are really endless. There is one problem with the above examples though: If the request fails for some reason, the progress is shown but never removed again. We can fix this by subscribing to the error event, where we can then remove the progress and then show an error message. Check out this example:


It's pretty much identical to the first example, but here we call the error function on the returned AJAX object and pass in a callback function which should be called if the request fails, which it will in this example, since I have changed the path for the requested file to something which doesn't exist.

0 comments:

Post a Comment

 

Sample text

Sample Text

Sample Text