JavaScript
Article
By Sam Deering

jQuery Ajax Loading using ajaxStart/ajaxSetup

By Sam Deering
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

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

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');
   }
});
Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?