Archive for July, 2006

Making AJAX calls onUnload

Friday, July 14th, 2006

I suppose this will be my first “official” developer blog entry, so bear with me if it seems a little sparse. This summer I’ve been doing a ton of work with object oriented Javascript and AJAX, and up until today the AJAX part has been mostly simplified by Atlas webservice proxies. However, today I hit one of those problems that just hasn’t been very well documented by anybody else, so I thought I’d write something about it.

Basically, our application keeps a form of session state server-side, and it needs to be notified when the browser window is closed or refreshed. Clearly, the thing to do here is to hook into the window.onUnload event (side note for new Atlas developers: don’t use window.onUnload, use Sys.Application.unload.add([yourUnloadHandler]) instead).

So at first I just went happily along, sending the usual XmlHttpRequest when the page unloaded. However, this of course poses a problem with the asynchronous response from the server: by the time the response comes back, the page has unloaded and the callback function won’t exist anymore. This generates an ugly Javacript “function is not defined” error. In any case, here’s a nice little picture of what happens:

AsynchronousJavacriptUnload

The solution here is to make sure that any AJAX requests that you make onUnload are make synchronously instead of asynchronously (SJAX?). This will ensure that the page doesn’t finish unloading before the server response comes back. Hence, the much happier picture below:

SynchronousJavascriptUnload

Bertrand Le Roy has a quick chunk of Javascript that you can use to do alter the XmlHttpRequest object to temporarily do only synchronous calls. Use this Javascript before any AJAX calls in your unload event, and you’ve solved your problem!