views:

28

answers:

1

I've been looking around for a while and haven't quite found what I've been looking for. My web page stores reports, and the user has the ability to save these reports.

I'm looking for a method, using jquery or the javascript onunload/onbeforeunload to ask the user if they wish to save the report or continue without saving when the browser is closed/navigated from.

Using onbeforeunload I can give the user the ability to stop navigation and manually save, although I would rather the save be done through the dialog box. Another problem with onbeforeunload is that clicking tags calls the onbeforeunload method too.

The save is asynchronous and takes a few milliseconds.

Any suggestions are welcome.

Regards, Byron Cobb.

+1  A: 

That is probably the only time a syncronized Ajax call is reasonable.

window.onbeforeunload = function(){
   $.ajax({
      url:      'somewhere',
      type:     'POST',
      dataType: 'text',
      async:    false,
      data:     'you_data_here',
      success:  function(data){
      }
   });
};

That way you should be able to transfer some ammout of data to your server, while the browser blocks the unload. That has some downsides. The most obvious, it's probably not that great user experience depending on how much data to transfer and how long it takes.
Another is that this method is not available in some (older) browsers.

A good alternative is maybe to autosave your data from time to time or after each action.

jAndy
I would happily change it to synchronous if the save functionality weren't already so depended on by other functions. I guess if thats the only way, I should look into changing the code.
Byron Cobb