Adding a Wait Cursor to a jQuery .ajax() Call

Category: jQuery/JavaScript Tags:
June 21, 2016
jquery

Adding a Wait Cursor to a jQuery .ajax() Call

When you make ajax calls there is often some delay before the response. When the response is more than a few seconds you may find the user clicking buttons again or taking some other undesirable action. A quick solution is to show a wait cursor, which will deter the user from any other actions and give them some kind of visual feedback that something is actually happening.

The trick is to add a CSS class to display the wait cursor at the start and then remove the class once the ajax operation is complete. The simplest CSS I’ve seen for this is:


html.wait, html.wait * { cursor: wait !important; }

but you can be more sophisticated if you like, such as dimming the background or even having some custom cursor.

I am assuming you are familiar with the jQuery .ajax function. Here is some typical code; on clicking a button you call an URL using .ajax() and simply display the result. Most times we just use the success or error functions but there is another function called complete which fires when the ajax request is over (whatever the result) and will occur after success or error.

So now all we have to do is display the cursor on click (just before the ajax call) and then remove it when the ajax complete fires.


$('#btn').click(function () {
  $('html').addClass("wait");

  $.ajax({
    url: "../myurl",
    data: { 'x': 1},
    datatype: "text",
    type: "POST",
    complete: function () {
      $('html').removeClass("wait");
    },
    success: function (data) {
      alert("All OK");
    },
    error: function () {
      alert("Sorry, there was an error");
    }
  });
});