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.

Bob
  • 3,074
  • 11
  • 43
  • 62
  • 1
    Why don't you always save, without annoying the user and allow for an easy undo the next time the user display the page ? "A report was automatically saved for you last time you closed the page [Undo]" – Julien Roncaglia Oct 19 '10 at 09:32
  • The problem with that is, the user can also create new reports and when saved have to name the report. I was thinking along those lines though. – Bob Oct 19 '10 at 09:37

2 Answers2

2

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
  • 231,737
  • 57
  • 305
  • 359
  • 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. – Bob Oct 19 '10 at 09:40
2
      $(document).ready(function() {
             //below turns off popup on a tags, buttons, :input is for a submit in ie and img tags
             $("a").click(RemoveUnload);
             $("button").click(RemoveUnload);
             $(":input").click(RemoveUnload);
             $("img").click(RemoveUnload);
         });

       RemoveUnload(){window.onbeforeunload = null;}
Pam Splitt
  • 21
  • 1