Disable ajaxStart() and ajaxStop() for a specific request
I figured it out..
There is an attribute in the options object .ajax()
takes called global
.
If set to false, it will not trigger the ajaxStart
event for the call.
$.ajax({
timeout: 35000,
url: longPollUrl,
success: function(data){
if(data.queCount) $('#numQueCount').html(data.queCount);
if(data.queAccept) $('#numQueAccept').html(data.queAccept);
},
global: false, // this makes sure ajaxStart is not triggered
dataType: 'json',
complete: longpoll
});
After reading all possible solutions, I want to combine answers.
Solution 1: Bind/Unbind
//binding
$(document).bind("ajaxStart.mine", function() {
$('#ajaxProgress').show();
});
$(document).bind("ajaxStop.mine", function() {
$('#ajaxProgress').hide();
});
//Unbinding
$(document).unbind(".mine");
It is a depreciated solution. Before jQuery 1.9, global events of ajax like ajaxStart, ajaxStop, ajaxError etc. can be binded to any element. After jQuery 1.9:
As of jQuery 1.9, all the handlers for the jQuery global Ajax events, including those added with the .ajaxStart() method, must be attached to document.
Therefore we cannot bind/unbind these events to custom namespaces.
Solution 2: Set the property global
to false
$.ajax({
url: "google.com",
type: "GET",
dataType: "json",
global: false, //This is the key property.
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
This solution works to disable ajaxStart()/ajaxStop()
event(s). However, it also makes disable ajaxComplete(), ajaxError(), ajaxSend(), ajaxSuccess()
. If you don't use these global events, it seems ok, but when it is needed, you have to come back and change your solution for all pages where you set global: false
.
Solution 3: Use global variable
var showLoadingEnabled = true;
$(document).ready(function () {
$('#loading')
.hide() // at first, just hide it
.ajaxStart(function () {
if (showLoadingEnabled) {
$(this).show();
}
})
.ajaxStop(function () {
if (showLoadingEnabled) {
$(this).hide();
}
});
});
function justAnotherFunction() {
window.showLoadingEnabled = false;
$.ajax({
url: 'www.google.com',
type: 'GET',
complete: function (data) {
window.showLoadingEnabled = true;
console.log(data);
}
});
}
Global variables should not be used in javascript files. However, this is the simplest solution, I can find.
I prefered the third solution for my project.