Your question is a bit vague. Your question implies that you're submitting the form asynchronously, but you said that you aren't familiar with JavaScript. Submitting a form asynchronously requires JS knowledge. Also, if you're actually submitting the form synchronously, the solution would have been too obvious (just render some JS conditionally on the server side).
If you're actually submitting the form asynchronously, then just set some token/toggle in as form's data-xxx
attribute after the succesful form submit. E.g.
function submit(form) {
// Do your thing to submit it.
// And then on succes:
form['data-submitted'] = true;
return false;
}
Then, during beforeunload
event you just check if the token/toggle is there and in case it's missing, return the message accordingly.
window.onbeforeunload = function() {
for (var i = 0; i < document.forms.length; i++) {
var form = document.forms[i];
if (form['data-submitted'] != 'undefined' && !form['data-submitted']) {
return "There is unsaved data!";
}
}
}
Note that you can't use unload
event for this since it too late then to keep the page open.
Update: so the form is submitted synchronously. Okay, whatever server side language you're using, just let it conditionally render a JS window.onbeforeunload
call when the form is not submitted (you obviously already know when the form is been submitted, how else would you be able to process it? ;) ). You also need to disable the window.onbeforeunload
call when the form is about to be submitted.
Based on your question history I bet that you know PHP, so here's a PHP targeted kickoff example:
<?php
if (!$form_is_submitted) {
echo '<script>window.onbeforeunload = function() { return "There is unsaved data!"; }</script>';
echo '<form onsubmit="window.onbeforeunload=null">';
}
?>