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.

Lind
  • 233
  • 1
  • 5
  • 14
  • 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. – bobthedeveloper May 13 '14 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 :) . – Lind May 13 '14 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` – bobthedeveloper May 13 '14 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. – Lind May 13 '14 at 18:21
  • You don't know if your request will be executed, as you can see [here](http://stackoverflow.com/questions/14929832/send-ajax-to-server-beforeunload). – rssilva May 13 '14 at 18:22
  • I don't know if I got, if you want a "automatic" submit, you can use $('#yourid button').trigger('click'); on in, but be careful about the unload method. Which Jquery version are you testing? – Lucas Haas May 13 '14 at 18:23
  • @rssilva so I may try to do the submitting and it may or may not fail ... – Lind May 13 '14 at 18:25
  • @LucasHaas I am not using jquery. I have not learned anything related to it :( – Lind May 13 '14 at 18:28

1 Answers1

1

Something like the following might work:

$(window).unload(function() {
  document.getElementById('YOURBUTTONID').submit();
});
eat-sleep-code
  • 4,753
  • 13
  • 52
  • 98
  • 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 ? – Lind May 14 '14 at 09:13
  • 1
    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. – eat-sleep-code May 14 '14 at 13:23