JavaScript
Article

jQuery Ajax Loading using ajaxStart/ajaxSetup

By Sam Deering

Quick jQuery code snippet examples on how to use jQuery.ajaxStart and jQuery.ajaxStop functions. Examples below.

Using ajaxStart and ajaxStop methods

The example below we have used it to display a loading image and disable a form submit button once it has been clicked while the ajax request is being processed. And then when it returns the image is hidden and the submit button becomes available again.

var $form = $('#form');

$form.find('.loading')
  .hide()
  .ajaxStart(function()
  {
      $(this).show();
      $form.find('.submit').attr('disabled', 'disabled');
  })
  .ajaxStop(function()
  {
      $(this).hide();
      $form.find('.submit').removeAttr('disabled');
  });

Using inserted code before ajax

Another method might be to add the image before the ajax call.

//show loading image, disable submit button
$form.find('.msg').remove();
$form.find('.loading').show();
$form.find('.submit').attr('disabled', 'disabled');

And then add a complete handler to the ajax function.

//hide loading image, enable submit button again
complete: function()
{
    $form.find('.loading').hide();
    $form.find('.submit').removeAttr('disabled');
}

Using ajaxSetup()

A further method is to use jQuery.ajaxSetup so that the image is hidden and form enabled when all ajax requests are returned “completed”.

$.ajaxSetup( {
   complete:function() {
      $form.find('.loading').hide();
      $form.find('.submit').removeAttr('disabled');
   }
});

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • http://midnightdesign.ws Brooks Boyd

    Note that for jQuery 1.6 and beyond, the “disabled” state of an element should be manipulated with the .prop() function, rather than .attr(), so “$form.find('.submit').prop('disabled', true);” and “$form.find('.submit').prop('disabled', false);” should be used instead.

  • Noob

    How are their scopes? Are they working on the whole jQuery object or other scope?

  • Guest

    adsad

  • Guest

    111

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.