clean_coding
clean_coding

Reputation: 1166

Unexpected javascript function behaviour

What I want is to add a loader bar to my HTML, while my method does some time consuming AJAX calls and DOM manipulation.

The problem is, that show() method won't show the loader bar until the AJAX calls are done, how do I fix this?

I want to force the show() method, then do AJAX calls and DOM stuff, then force the hide() method.

Method doing AJAX calls:

$('.my-button').on('click', function(){
   $('#display-loader').show();
   // ajax and dom manipulation
   $('#display-loader').hide();
});

EDIT: Seems like there's some misunderstanding as to what my problem is. If I change my code to this:

$('.my-button').on('click', function(){
   $('#display-loader').show();
   // ajax and dom manipulation
});

It still won't SHOW the loader bar, untill the AJAX methods are done, it's like it skips the show() method, does AJAX stuff, and then calls the show() afterwards.

All the AJAX calls have async set to false. I have 5 AJAX calls, and each AJAX call relies on the data fetched from the previous call, I have no way to set the async to true, is there a way to get around this, and force the DOM to display the image, and then do AJAX calls?

Upvotes: 0

Views: 96

Answers (3)

Jeandre Pentz
Jeandre Pentz

Reputation: 1002

I recommend maybe the following way:

$.ajax({
  .....
}).done(function () {
  hideLoader();
});

This will insure the loader goes away. If your ajax isn't successful then the success callback will never be reached and then the loader will stay on the page.

But it depends on the scenario. You can also just put it in your error callback.

Upvotes: -1

thecodeparadox
thecodeparadox

Reputation: 87073

You need to call hideLoader() within AJAX success function, to hide after ajax operation. As AJAX is asynchronous, so in your code hideLoader() execute before finish ajax call and done dom stuff.

$('.my-button').on('click', function(){
   showLoader();
   $.ajax({
     ....
     success: function() {
          hideLoader();
     } 
   });
});

according to @Esailija comment to hide after complete callback do like:

$('.my-button').on('click', function(){
   showLoader();
   $.ajax({
     ....,
     success: function(){

     },
     complete: function() {
         hideLoader();
     }
   })
});

Upvotes: 1

falinsky
falinsky

Reputation: 7428

you can do next:

showLoader();
$.ajax({
   type : 'POST',
   url : url,
   data : postData,
   success : function (returnData) {

   },
   error : function (xhr, textStatus, errorThrown) {

   },
   complete : function (){
       hideLoader();
   }
});

Upvotes: 1

Related Questions