Saturday, January 31, 2015

How to ignore global Ajax error handler for user aborted requests using jquery

We had this situation in one of my project, where we wanted to bypass the jquery global Ajax error handler if user aborts the Ajax request by navigating away from the page (for example, by clicking a link on the page)

I tried various options but none seem to work. Finally, I came across one solution, that seem to work perfectly well for my situation.

The idea behind this perfect solution is,
  • Bind the "beforeunload" event on the window object.
  • In the event handler, set a global variable to indicate that the page is being unloaded. 
  • In the global Ajax error handler, do not take any action if the above global variable is set.
  • In all other cases, perform the actual Ajax error handling.
Lets quickly look at the JS code as well.

The code is pretty self explanatory and well documented.  That's about all it takes to get the job done! 

Have some Fun!