Autosave with "unload" event and ajax call on logout : order of actions is causing an issue Autosave with "unload" event and ajax call on logout : order of actions is causing an issue ajax ajax

Autosave with "unload" event and ajax call on logout : order of actions is causing an issue


ori's answer is correct and complete.

But judging from your case you could use a workaround.

There are two JavaScript features you might be interested in:localStorage and sessionStorage (it's the same except the second one is cleared on browser close, so you probabli will choose the first)

The idea is to save data to localStorage with some metadata stating if changes were saved. If the user leaves the page but goes to another page in your service, or even returns later - you can send the data again with some information that it was not saved due to page unload.

Proof of concept code:

$(window).bind('unload', function() {    localStorage.setItem('unsavedData',data);    localStorage.setItem('unsaved',true);});$(document).ready(function(){    if(localStorage.getItem('unsaved')){       //ajax send        localStorage.setItem('unsaved',false);    }});

[edit]

I have been successfully using JSONP with unload and it seemed to work most of the times, but I haven't tested it under load and on slow network.


No. You can only display a confirm dialog to the user:

$(window).bind('beforeunload', function() {    // AJAX    return 'STRING';});

The STRING will be displayed in the dialog, and then you might have time for the reponse to come back before user reacts.

But that's the only way you can block a page from unloading, hence the ajax response will not be received.


What about a fixed transparent div across the top of your page with a hover event to fire the save? Just thinking form a creative point of view... Keep the save you have now, but as a failsafe, I'm thinking if the average user is going to navigate away, first they will move the mouse to the address bar, back button, or close button. If you capture the top of the DOM Window, maybe get a few more successful last-minute saves?

Also, you could push the changes on a setTimeout() but it sounds like you're going for something more finite than both of my solutions.