jQuery Ajax Loading using ajaxStart/ajaxSetup

Sam Deering
Share

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');
   }
});