How to Show different loading images for different AJAX calls in jQuery

How to Show different loading images for different AJAX calls in jQuery

Suppose you have a page where different AJAX calls are taking place and you want to indicate your users which AJAX call is currently taking place. You can indicate this by showing different loading images for different AJAX calls.

Traditional Approach Fails

The traditional .ajaxStart() and .ajaxStop() events cannot be used in this situation as they are called on each and every AJAX call.

Take for example the following jQuery code:

$(document).ajaxStart(function () {
$(document).ajaxStop(function () {

The .ajaxStart() and .ajaxStop() events are applied on the document object which makes them useless in case you want to show different loading images.

The Correct Approach

To show different loading images for different jQuery AJAX calls you have to use custom namespaces. By using these custom namespaces you can bind and unbind from AJAX events.

Let me show how to do it for 2 buttons, both of them do an AJAX call. On the click of first button I will show the image 1 while that of second one will show the image 2.

loading image for first button click loading image for second button click

First create the 2 buttons and 2 img tags on your page:

<button id="button1">Button 1</button>
<img id="loadingImg1" src="loading1.gif" />
<button id="button2">Button 2</button>
<img id="loadingImg2" src="loading2.gif" />

Then create the click events of these 2 buttons:

$("#button1").click(function (e) {
    $(document).on("ajaxStart.firstCall", function () {
    $(document).on("ajaxStop.firstCall", function () {
    return false;
$("#button2").click(function (e) {
    $(document).on("ajaxStart.secondCall", function () {
    $(document).on("ajaxStop.secondCall", function () {
    return false;
function AjaxCall() {
    $("button").prop("disabled", true);
        type: "POST",
        url: "index.aspx/myfunction",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result, status, xhr) {
            $("button").prop("disabled", false);
        error: function (xhr, status, error) {
            alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)

Code Explanation:

  • The .firstCall is the namespace of the first button and .secondCall is the namespace of second button.
  • On the button click I am unbinding the other button’s namespace with the .off() method.
  • Then I am binding the button’s namespace with the .ajaxStart() and .ajaxStop() events.
  • In these event the corresponding loading image is shown or hidden.

Check the below link:



  • linkedin
  • reddit


I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate