views:

178

answers:

3
   $.ajax({
       url: "/cgi-bin/stats.exe",
       method: "post",
       async: false,
       data: { refresh: "a41" }
   });

Using ajax post synchronously - "async: false".

While it blocks the browser during the active request, what is the most efficient way to change the cursor to the hourglass or display a wait .gif?

Perhaps set the cursor as it enters this function then change it back in the success or complete function?

Any advice is appreciated.

Thank You.

+3  A: 

Don't make the request synchronous because it will totally block everything else. Instead, you can use an asynchronous request, but make it look like it's synchronous by "blocking" the UI. I use jQuery.blockUI() for this.

Matt Ball
I also do it like this, pretty cool.
Cipi
Very nice. However, I do need to make sure the page does not load until after the request for this particular case, but it seems I should still be able to do that with the plug in?
Tommy
What do you mean by "make sure the page does not load?" Make sure the browser stays on the current page? That kind of thing is pretty much outside of your control. You really shouldn't force a user to stay on a particular page - and what if they kill their browser?
Matt Ball
@Bears: Clearly, if they kill their browser, bears will eat them.
R. Bemrose
+2  A: 

I haven't tested this, but I think it would be done like so:

$('html, body').css('cursor', 'wait');

$.ajax({
   url: "/cgi-bin/stats.exe",
   method: "post",
   async: false,
   data: { refresh: "a41" },
   success: function() {
     $('html, body').css('cursor', 'auto');
     // the rest of your processing here
   },
   error: function() {
     $('html, body').css('cursor', 'auto');
   }
});

Per @patrick's suggestion, changed it back on error as well.

Hooray Im Helping
Should probably also change it back in the `error:` callback.
patrick dw
Seems like any functionality I put before the ajax post, still happens after the post..? i.e. changed the cursor before and it changes it after the post. (same issue with the block screen)
Tommy
@Hooray, You can avoid duplicating the code by changing the cursor in the `complete:` instead of in `success:` and in `error:`
Rosdi
@Tommy, thats because you set `async: false`. Remove that line and it will work.
Rosdi
+1  A: 

I recommend using the jQuery blockUI plug-in. It will change the cursor, show any message or icon (http://ajaxload.info/) you like while the user is waiting. There's lots of info on the website for how to use it, but in its simplest form:

$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);

That will automatically show the wait cursor and prevent user activities until the ajax call completes.

Adam