views:

409

answers:

2

I currently have form that checks if a user has unsubmitted changes when they leave the page with a function called through the onunload event. Here's the function:

function saveOnExit() {
    var answer = confirm("You are about to leave the page. All unsaved work will be lost. Would you like to save now?");
    if (answer) {
       document.main_form.submit();
    }
}

And here's the form:

<body onunload="saveOnExit()">
<form name="main_form" id="main_form" method="post" action="submit.php" onsubmit="saveScroll()">
    <textarea name="comments"></textarea>
    <input type="submit" name="submit2" value="Submit!"/>
</form>

I'm not sure what I'm doing wrong here. The data gets submitted and saved in my database if I just press the submit button for the form. However, trying to submit the form through the onunload event doesn't result in anything being stored, from what I can tell. I've tried adding onclick alerts to the submitt button and onsubmit alerts to the form elements and I can verify that the submit button is being triggered and that the form does get submitted. However, nothing gets passed stored in the database. Any ideas as to what I'm doing wrong?

Thanks.

+1  A: 

Try onbeforunload

An event that fires before the unload event when the page is unloaded.

Also give return false at the end of the function for the condition in which the data should not be submitted.

rahul
Thanks for the onbeforeunload suggestion. I retweaked my code and got it to work in a different way.
holic87
A: 

And make sure, that you don't do any async form submitting (i.e. in saveScroll). As soon as your window.onbeforeunload function returns, all ajax calls are interrupted.

aeby