I've designed a form in my website. my form has a timer for submission. my question is : if a user decide to leave the page and doesn't want to submit the form anymore, is there a way to submit form before he/she leave/close/refresh the page ?
Asked
Active
Viewed 2,501 times
0
-
2Yes, already answered here: [https://stackoverflow.com/questions/13443503/run-javascript-code-on-window-close-or-page-refresh#13443562](https://stackoverflow.com/questions/13443503/run-javascript-code-on-window-close-or-page-refresh#13443562) – geoidesic Feb 17 '18 at 21:07
-
@geoidesic but ,are you sure it is exactly what i want ? i mean "onbeforeunload" try to convince user to not leave the page and he would click on stay button to stay on the page ,but i want to submit the form when a user want to close or refresh the page without confirmation even needed – Naderjlyr Feb 17 '18 at 21:10
-
Some more info here https://stackoverflow.com/questions/20001125/beforeunload-or-onbeforeunload – user9263373 Feb 17 '18 at 21:11
-
It's been asked before without the confirmation dialog and it's here: https://stackoverflow.com/questions/1631959/how-to-capture-the-browser-window-close-event – geoidesic Feb 17 '18 at 21:23
-
@geoidesic no, this solution exclude form submission from confirmation. what i need is when a user want to refresh or close the page , form auto submit itself without permission of user – Naderjlyr Feb 17 '18 at 21:34
1 Answers
2
Do this to detect page close:
window.onbeforeunload = closingCode;
function closingCode(){
document.getElementById("form").submit();
return null; //<-- this prevents the dialog confirm box
}
It won't trigger on refresh. That you will have to do on the back-end - i.e. track visits to that page by that session / ip address.
However I would say that you are approaching this the wrong way. Rather than trying to submit before they leave. Submit onChange event for the form and / or it's fields using a threshold.
Here's the full example. HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="refreshForm" id="form" action="form.php">
<input type="text" name="visited" value="" />
<input type="text" value="hello" />
<input type="submit" />
</form>
<script>
window.onbeforeunload = closingCode;
function closingCode(){
document.getElementById("form").submit();
return null;
}
</script>
</body>
</html>
PHP (form.php)
<?php
file_put_contents('log.text', $_REQUEST);
This doesn't do anything useful but you will see it creates the file and writes to it.

geoidesic
- 4,649
- 3
- 39
- 59
-
-
I can but that's a different question and it's probably already answered elsewhere if you google: https://stackoverflow.com/questions/329805/submit-form-when-elements-change – geoidesic Feb 17 '18 at 21:57