Prevent form resubmission alert POST method – PHP

When you submit a form with a POST request and if you refresh that page, you will see an alert that says “Confirm form resubmission”. This is not good for the user experience. You cannot use the GET method because it will make the URL look bad. But we still need to prevent this form resubmission alert dialog.

So using this technique, you can achieve both. Submit the form without making the URL bad, and prevent the “form resubmission” alert.

Suppose you have a form with an input field that sends a POST request like the following:

<form method="POST" action="form-submit.php" onsubmit="return onFormSubmit(this);">
    <input type="text" name="name">
    <input type="submit">
</form>

Attach an event named “onsubmit” to the form tag that calls a Javascript function named “onFormSubmit”. The return statement is used to prevent the form from submitting. Now, create that function in Javascript:

<script>
    function onFormSubmit(form) {

        // create data object with all form values
        var data = {
            "name": form.name.value
        };

        // convert in JSON
        var jsonData = JSON.stringify(data);

        // save in cookies
        document.cookie = "my_form=" + jsonData;

        // redirect to form's action
        window.location.href = form.getAttribute("action");

        // prevent form from submitting
        return false;
    }
</script>

Comments have been added with each line for an explanation. You can write all your form fields in the data object. If you have an input type=”file” field in your form, you can add it to the data object by calling the files property like the following:

var data = {
    "image": form.image.files[0]
};

For multiple files, you can simply remove the [0] from the above line and it will add all files in the data object.

Now on server-side, do the following to get the values:

<?php

    // get in server side
    $my_form = $_COOKIE["my_form"];

    // decode from JSON
    $my_form = json_decode($my_form);

    // get single value
    $name = $my_form->name;

    print_r($name);
?>

As we were storing the values in cookies using Javascript, so we can get them from cookies using PHP.

As we were storing the values in JSON string using Javascript. So, we can get them by decoding from JSON string using PHP.

That’s how you can prevent the “form resubmission” alert and also keep your URL clean from GET request.

[wpdm_package id=’949′]

Posted in PHP