Javascript onunload form submit isn't submitting data

Posted by Kevin on Stack Overflow See other posts from Stack Overflow or by Kevin
Published on 2010-04-16T07:49:55Z Indexed on 2010/04/16 7:53 UTC
Read the original article Hit count: 347

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.

© Stack Overflow or respective owner

Related posts about javascript-events

Related posts about onunload