I'm using a AutoSave feature on an online editor.
When an user leaves the page (detected with unload
or beforeunload
event), I'm sending a AJAX request (async = false) to save the data.
I have a problem in Firefox et sometimes in Chrome because that serie of events is happening :
Of course since the user has been disconnected the "save" request can't be handled.
Is there a way, compatible with all browsers, to wait for the response of the AJAX call, before the page actually changes ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With