0

Let's suppose I have a form with some input fields and a submit button.

If I use the window.onunload, is it possible for me to trigger the submit button before the user leaves the webpage.

Which would be the correct way to implement it.

8
  • 1
    Why would you want to submit the form without having the users 'approval' and without them knowing it? - You could save the input fields in the localStorage/a cookie and show the values when the user comes to the form again. Commented May 13, 2014 at 18:18
  • @Hatsjoem I am creating a project in php which is an online test exam website. I still want to get the user results even if he wants to leave, or refresh the page. This is a project which is required by my teacher so I have no other choice on that matter :) . Commented May 13, 2014 at 18:20
  • What if he doesn't fill al the fields in? Just doesn't make a lot of sence to me, but yes you could save the exam on window.onunload Commented May 13, 2014 at 18:21
  • @Hatsjoem the user can't resume the test if he leaves. Then the admin has a table with the user's name and 0 points attached in it. Commented May 13, 2014 at 18:21
  • You don't know if your request will be executed, as you can see here. Commented May 13, 2014 at 18:22

1 Answer 1

1

Something like the following might work:

$(window).unload(function() {
  document.getElementById('YOURBUTTONID').submit();
});
Sign up to request clarification or add additional context in comments.

2 Comments

Let's say my idea is to use this button to submit the form to the same page. At that page I have the php script which checks if the button is submitted and does stuff. As of your own experience will this stuff be executed most likely ?
If you post to the same page, you would need to wrap the document.getElementById line with some sort of logic to see if it really should be submitting. Otherwise you risk getting a submit loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.