window.unload, synchronous ajax and page loads

I’ve been working on a project that had me work with javascript based timers and required me to ensure certain data was updated before the user left the page. The obvious solution in this case was to handle the data updating on the window.unload event.

Now the task at hand was to ensure that on unload the quiz status (the object i was working with) needed to be updated to ‘DONE’ or something to that effect and the next object that was in the ‘NEW’ state needed to be fetched.

Synchronous AJAX (or whatever synchronous XMLHttpRequests are called)
The problem with using asynchronous ajax in such a situation would be that one cannot guarantee if the page refresh or a new request would wait long enough to see through the ajax request. Chances are the page may unload much before you receive confirmation that the request was completed. The advantage with synchronous ajax is that the page waits in a frozen state awaiting a confirmation before it loads the next request. Sync ajax in jquery

In most scenarios you would not need to have that confirmation but heres one valuable detail that I overlooked and may come in handy:

When you wait on a response the next request (which could have been caused by clicking a link or a refresh) to the server has already loaded and is waiting to be rendered while you wait on the unload event to display the confirmation of your cleanup action. In my case this was updating the state of the quiz object from new to done.

What I failed to acknowledge was that the new request is processed before the server actually receives the message from your ajax call. So if your next request depends upon the clean up action performed by your ajax call, the data that is waiting to be rendered is already stale (as it was fetched by working on data before the ajax updation took place)

Just to drive the point home, here are the sequence of events
1. Click Link/Refresh
2. Request for refresh or click fired
3. window.unload event fired (Response from the earlier request waiting to be rendered)
4. ajax call to update data on the server (Response from the earlier request waiting to be rendered)
5. ajax callback received
6. Data for click link/refresh rendered.

* the sequence is purely to illustrate the point.

A optimal solution would be to use filters if your using Rails.

This may sound trivial for most experienced developers but in case you overlooked this I hope this post saves you some time.