As I’m sure you guessed from earlier posts, I’m using BlockUI in an MVC application. I have various calls using jQuery’s $.ajax method throughout my application. For the majority, I want to show a “Please Wait” message, and BlockUI makes this simple. Since most of my calls need that functionality, I simply use the following:

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

Greedy == Problems

The greedy approach works just fine until you have a call where you don’t want to use BlockUI. For example, in my application I have various forms inside modal windows, which block the background already. While the user is interacting with the form, I make various Ajax calls to get additional data or to perform remote validation. Every time I make a call, the user ends up seeing a flash on the screen because the background of the modal window (which is transparent black) ends up getting stacked with the background of BlockUI (also transparent black). Not a great experience. It reminds me of the early days of the web with flashing and flickering tricks that you’d see on many sites. Besides aesthetics, it is just confusing for the user.

Options

What are the solutions? Well, you could use BlockUI “manually” by calling $.blockUI() when you want to block the page and then calling $.unblockUI() in a callback to, well, unblock the page. That’s not always an easy pattern to follow. If you are using 3rd party components that make $.ajax calls internally and you want to block the page, then the ajaxStart/ajaxStop approach may be easiest. Also, if ~95% of your calls need the functionality, why specify it everywhere? Thankfully, there is a way to have your cake and eat it too.

Solution

If you head over to the jQuery docs for ajaxStart, you’ll find the solution in the Additional Notes section:

If $.ajax() or $.ajaxSetup() is called with the global option set to false, the ajaxStart() method will not fire.

W00t! That’s a simple solution for our issue, and in my testing, it works perfectly. Just set global: false and now there’s no more weird background flickering.

During my search for the answer, I came across another technique that works as well. This solution may be preferred if you have other things that happen during the ajaxStart event.