Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 :

  • event fired
  • request send
  • the page change and the user is disconnected
  • request analysed by the server => problem !
  • request response received by browser

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 ?

like image 555
Loïc Février Avatar asked Jun 13 '11 17:06

Loïc Février


1 Answers

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.

like image 191
naugtur Avatar answered Sep 24 '22 03:09

naugtur