1

I need to do a postback from my application when a user decides to navigate away/close the page. I think I might be able to do this with javascript. I've tried window.onunload and window.unload, but neither seem to be able to actually do a postback here:

<script type="text/javascript">
    window.onunload = function() {
        document.forms[0].submit();
    }
</script>

My scenario: I have a form that I want to capture data from if the user decides to quit in the middle of filling it out. It's quite lengthy, so I'd like to save the data so they can continue working on it later.

Maybe it might be better to do some timed event?

Thanks to anyone who can help!

Jack
  • 950
  • 2
  • 17
  • 36
  • You might check out this answer: http://stackoverflow.com/questions/3775566/javascript-question-onbeforeunload-or-onunload/3775590#3775590 I think you'll see different results depending on the browser. – NotMe Oct 17 '13 at 02:45

2 Answers2

1

You could save the form's values within a cookie, and load that cookie when your visitor comes back.

With jQuery it's fairly easy:

$( window ).unload(function() {   
$.cookie("cookie_name", "cookie_value", { expires: 7 } // Possible options ); 
});

Then on page load you could try something like this:

if (var cookieValue = $.cookie("cookie_name"))
$(yourfield).val()=cookievalue;

Keep in mind that if you need to save multiple values you could create a json string and store it within the same cookie.

See Jquery cookies

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
Mat
  • 38
  • 1
  • 7
  • I guess that's probably the best solution. I was kind of hoping to avoid having to save all that manually. How would I do an image or something like that? – Jack Oct 17 '13 at 02:40
  • @Jack: What do you mean do "do an image"? As in save a file upload or something else? – NotMe Oct 17 '13 at 02:44
  • @Jack: Usually you'd have to save the file within your website and then save it's url within your cookie if you want to use it again. – Mat Oct 17 '13 at 03:08
0

Try

<script type="text/javascript"> window.onbeforeunload = function() { document.forms[0].submit(); } </script>
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58