VeeeneX VeeeneX - 3 months ago 17
jQuery Question

Show/Hide jQuery does not work with Ajax

Hi I have a problem with following code:
I can't hide loading.
I've tried Mozilla,Chrome and it only works when you paste it to console.
Html of Loading on Start

<div class="loading" style="display: none">


After .show

<div class="loading" style="display: block;">


Ajax

$.ajax({
url: "/uzemnenie",
cache: false,
async: true,
dataType: "html",
success: function (data) {
console.log("in ajax ", data.slice( 0, 100 ));
$('.content').empty().html(data);
}
});


Code on webpage

$( document ).ajaxStart(function() {
$(".content").fadeOut( "slow", function() {
$(".loading").show().css("display", "block");
});
});

$( document ).ajaxStop(function() {
$(".loading").hide();
$(".content").fadeIn("slow", function() {
$('#show').fadeIn("slow");
});
});


Works only when:

$( document ).ajaxStop(function() {
$(".loading").css("display", "none");
$(".content").fadeIn("slow", function() {
$('#show').fadeIn("slow");
});
});


Weird part - Content is added too

$( document ).ajaxStop(function() {
$(".loading").hide(function(){
$(".content").fadeIn("slow", function() {
$('#show').fadeIn("slow");
});
});
});


And content is displayed right.
Thanks for answers.

Answer

Ok, finally it's very simple. The ajax request is faster done then you expected. Because of this the data you hide or show in ajaxStart isn't being processed completely while the request is already finished. So what you're doing in the ajaxStop function is being messed up by the end of show/hide functions you called previously in ajaxStart. This is the trap of asynchronous request. The easiest way around is to add a setTimeout().

You can see the working solution here jsfiddle.

$(document).on({
  ajaxStart: function() { 
                    $(".content").fadeOut("slow");
                    $(".loading").show();
  },
  ajaxStop: function() {
      setTimeout(function() { 
                     $(".loading").fadeOut("slow");
                     $(".content").show("slow");     
                  }, 1500);                                        
  }    
});
Comments