views:

67

answers:

2

Hi, I am using the following code to capture all the AJAX calls being made from my app, in order to show a busy spinner till the call is completed. It works well when the requests are well spaced out. However, when the request are made in quick successions, some of the AJAX calls do not get registered, or the onCreate and onComplete actions get kicked off at the same time, and more often than not, the busy spinner continues to appear on the screen, after all the calls have successfully completed. Is there any check I can perform at the end of the call, to check if the element is visible, I can hide it.

document.observe("dom:loaded", function() {
$('loading').hide(); 
Ajax.Responders.register({
//When an Ajax call is made. 
onCreate: function() {
new Effect.toggle('loading', 'appear');
new Effect.Opacity('display-area', { from: 1.0, to: 0.3, duration: 0.7 });
},

onComplete: function() {
new Effect.toggle('loading', 'appear');
new Effect.Opacity('display-area', { from: 0.3, to: 1, duration: 0.7 });
}
});
});

Thanks!

+2  A: 

A simple approach would be to create a counter variable that has scope outside your two functions and increment it in onCreate and decrement in onComplete. Then only hide the spinner when the counter hits 0.

bmoeskau
+1  A: 

You need to keep a count of how many AJAX requests are processing, and only hide the loading indicator if no further requests are processing.

Try code similar to the following:

document.observe("dom:loaded", function() {

  var ajaxRequestsInProgress = 0;

  $('loading').hide(); 

  Ajax.Responders.register({
    //When an Ajax call is made. 
    onCreate: function() {
      if(!ajaxRequestsInProgress)
      {
        new Effect.toggle('loading', 'appear');
        new Effect.Opacity('display-area', { from: 1.0, to: 0.3, duration: 0.7 });
      }
      ajaxRequestsInProgress++;
    },

     onComplete: function() {
       ajaxRequestsInProgress--;
       if(!ajaxRequestsInProgress)
       {
         new Effect.toggle('loading', 'appear');
         new Effect.Opacity('display-area', { from: 0.3, to: 1, duration: 0.7 });
       }
     }
  });
});
Josh
Thanks! Works like a charm. Both the answers suggested by bmoeskau and Josh convey the same idea!
Gunner4Life
That's because great minds think alike ;-)
Josh