Aldi Unanto
Aldi Unanto

Reputation: 3682

Prevent ajax load animation in specific case

I have global ajax load animation that runs in every ajax called. But in this case, I want to disable that effect. How can I do that?

This is for global animation :

$(document).ajaxStart(function(){
   $('#ajax-loader').show();
}).ajaxStop(function(){
   $('#ajax-loader').fadeOut(200);
});

And below the code that I won't to show the animation.

setInterval(function(){
   chat_notif(); //function that contain an ajax call
}, 1000);

Upvotes: 0

Views: 143

Answers (2)

Konstantin Krass
Konstantin Krass

Reputation: 8646

You can seperate by checking the xhr or options from the ajaxSend()

var ajaxXhr, ajaxOptions;
$(document).ajaxSend(function(event, xhr, options) {
   ajaxXhr = xhr;
   ajaxOptions = options;
}).ajaxStart(function(){
   if(ajaxXhr || ajaxOptions ) //something that detects the specific case
    $('#ajax-loader').show();
};

jquery - Can I retrieve (event, xhr, options) from .ajaxStart or .ajaxStop?

Usage:

Lets say you want to go for the url "/rest/refreshChatNotifications", this url will be within the XHR or options (i guess in xhr). Now you can use the if within the ajaxStart to check against this url.

var ajaxXhr, ajaxOptions, refreshChatUrl = "/rest/refreshChatNotifications";
$(document).ajaxSend(function(event, xhr, options) {
   ajaxXhr = xhr;
   ajaxOptions = options;
}).ajaxStart(function(){
   if(ajaxXhr.url !=  refreshChatUrl ) //if it's the specific url, dont show
    $('#ajax-loader').show();
};

if you have multiple urls, that shouldn't show animations, do it like this:

var ajaxXhr, ajaxOptions;
var dontShowAnimationForUrls = ["/rest/refreshChatNotifications", "/rest/anotherAjaxWithoutLoader"];
$(document).ajaxSend(function(event, xhr, options) {
   ajaxXhr = xhr;
   ajaxOptions = options;
}).ajaxStart(function(){
   if(dontShowAnimationForUrls.indexOf(ajaxXhr.url) < -1) //if it's the specific url, dont show. Index will be > -1, then url found.
    $('#ajax-loader').show();
};

Upvotes: 1

Baseleus
Baseleus

Reputation: 162

Perhaps you could add a global boolean variable showAjaxAnimation with default value true. In the setInterval you could make something like that.

setInterval(function(){
   showAjaxAnimation = false;
   chat_notif(); //function that contain an ajax call
   showAjaxAnimation = true;
}, 1000);

And then in the AjaxStart you could do:

$(document).ajaxStart(function(){
   if (showAjaxAnimation)
     $('#ajax-loader').show();
}).ajaxStop(function(){
   $('#ajax-loader').fadeOut(200);
});

Upvotes: 0

Related Questions