1

I've made a short game in which people give answers to sequentially-presented questions, and in which their scores are stored in variables that are updated with every right answer (ie. var Score = 0; function ScoreUpdate {if (event.keyCode == correctAnswer) {Score = Score +1;}}). At the end, a JavaScript function is called that puts these variables into a form and subsequently "POST"s it to a page which then adds everything to a MySQL database.

The problem is that some people will stop half-way and simply close the window/tab, causing none of the scores to be submitted (as the JavaScript function to put all variables into the form and submit it isn't activated). I'm thus looking for a way that will automatically activate the function to save the scores, submit the form and upload to the database when the user closes the window. This involves both PHP and JS, hence I'm wondering whether all of this is even possible in just one event? (ie. window.onbeforeunload?)

I've tried this solution: https://stackoverflow.com/a/1632004/1092247 but it does not include automatic form submission (it doesn't even work in general for me, as it still prompts even when form is submitted).

As you can see I'm relatively new here, with far from advanced JS and PHP knowledge. Any help would be very much appreciated! :)

Community
  • 1
  • 1
rvrvrv
  • 881
  • 3
  • 9
  • 29
  • 1
    I would recommend to submit data to server on every answer instead of updating your result locally and then submitting at the end of quiz. This way you will be able to at least store some of the results if they quit in the middle of quiz – Dmitri Snytkine Jan 31 '12 at 16:07

2 Answers2

2

You can't submit a form if a user closes a window. The only thing you can do is ask for confirmation (i.e. "Do you really want to close the window?").

Unfortunately there is no way around it. JavaScript will simply not allow you to do that.

MMM
  • 7,221
  • 2
  • 24
  • 42
1

If you really want to save all those intermediate results, then send them after every answered question.

You'll probably have to introduce some kind of a session, so that you gradually build full result on the server out of incoming individual answers.

This will somewhat increase load on your server, though.

You can be somewhere in between those two extremes (loss of intermediate results <===> high server load). For example, still accumulate answers somewhere and send them to the server every N seconds.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367