views:

34

answers:

1

I have a form on a webpage.when the user moves from that page, I want to check that the form was submitted. If it was, then the user simply continues to the next page, if not, the user receives an alert msg and is brought back to the original page where the form resides.

I am not too familiar with javascript so I would appreciate some code snippets if that's possible?

GF

A: 

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">';
    }
?>
BalusC
Hi,Thanks for you answer. Actually the form will be submitted Synchronously.So I want to check the "beforeunload" function that the form has indeed been submitted.if it has, nothing happens, if not, the user is brought back to the form.I hope this is clear?GF
It is not possible to force them to stay on the same page. It is, however possible to show a message that asks them whether they want to stay on the same page, then focus the form.
Hello71