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.
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 () {
$("#loadingImg").show();
});
$(document).ajaxStop(function () {
$("#loadingImg").hide();
});
The .ajaxStart() and .ajaxStop() events are applied on the document object which makes them useless in case you want to show different loading images.
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.
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).off(".secondCall");
$(document).on("ajaxStart.firstCall", function () {
$("#loadingImg1").show();
});
$(document).on("ajaxStop.firstCall", function () {
$("#loadingImg1").hide();
});
AjaxCall();
return false;
});
$("#button2").click(function (e) {
$(document).off(".firstCall");
$(document).on("ajaxStart.secondCall", function () {
$("#loadingImg2").show();
});
$(document).on("ajaxStop.secondCall", function () {
$("#loadingImg2").hide();
});
AjaxCall();
return false;
});
function AjaxCall() {
$("button").prop("disabled", true);
$.ajax({
type: "POST",
url: "index.aspx/myfunction",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result, status, xhr) {
alert(result.d);
$("button").prop("disabled", false);
},
error: function (xhr, status, error) {
alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
}
});
}
Code Explanation:
Check the below link: