-1

Whenever a user submits my form and then refreshes the page, it resubmits the form.

Here is my stripped down HTML:

   <form action="" method="post" id="myform">
        <input type="text" name="title">
        <input type="submit" value="Submit" name="subnewtopic" /> 
   </form>

How can I prevent the form from resubmitting upon refresh?

3

2 Answers 2

3

You need something server-side to handle this. Commonly people use a server-side language (PHP, JSP etc) to handle the post and then redirect to another page. This is a Post/Redirect/Get pattern (PRG) .

Simply put:

  1. The user submits (POSTs) the form.

  2. The POST is handled by your (server-side) code that does something with the request data (eg: populates a database) and then REDIRECTs to a new page (eg: thanks.php) or the same page.

  3. The page optionally GETs the data (from the db or passed parameter etc) to display to the user.

If the user refreshes the browser they are merely refreshing the thank-you page/view NOT resubmitting anything.

JavaScript Alternative..?

Without something server-side (recommended) you are going to have to use JavaScript.

I would not recommend this but if you have no better options you could use JS to set a cookie when the form is submitted unless the cookie already exists - in which case don't submit at all.

Something like:

document.forms["myform"].onsubmit = function(){
    //See: https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
    if (document.cookie.replace(/(?:(?:^|.*;\s*)submitted\s*\=\s*([^;]*).*$)|^.*$/, "$1") !== "true") {
        document.cookie = "submitted=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
        return true;
    } else {
        //cookie exists, dont submit
        return false;
    }
}
<form name="myform" method="post">
    <input type="submit" />
</form>

Update!

It occurred to me that restricting the form submission if a cookie exists is a bad solution as it does not stop the refreshing of the browser but just stops the user using the form more than once. Sorry ;)

So how to the stop the form being resubmitted if the user refreshes the page?

To reiterate: use something server-side. If you must have a JS solution you could submit the form via AJAX or implement the following simple PRG inspired solution to forward/redirect the page if a certain parameter has been passed (indicating that the form was submitted):

<div id="formWrapper">
    <p>Please submit the form</p>
    <form>
        <input type="submit" name="submitted" value="submit" />
    </form>
</div>

<script>
    /* method to fetch params from the query string */
    function getQueryParams() {
        var qs = document.location.search;
        qs = qs.split("+").join(" ");
        var params = {}, 
            tokens,
            rx = /[?&]?([^=]+)=([^&]*)/g;
        while (tokens = rx.exec(qs)) {
            params[decodeURIComponent(tokens[1])]
                = decodeURIComponent(tokens[2]);
        }
        return params;
    };

    //get the params:
    var params = getQueryParams();

    //test if our 'submitted' param has been passed:
    if(params.submitted){
        //if it has, then reload the page without params
        location = location.protocol+'//'+location.host+location.pathname+"?thanks=true"
    }

    //test if our 'thanks' param has been passed:
    if(params.thanks){
        //if it has been passed we can show the thanks message in place of the form...
        document.getElementById("formWrapper").innerHTML = "Thanks. Your form was submitted and I did something with it. You can refresh this page if you like.";
    }
</script>
-2
//Check this out mate!!

//This is working !!!

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("form").submit(function(){
    event.preventDefault();
  });
});
</script>
</head>
<body>

<form action="">
First name: 
<input type="text" name="FirstName" value="Mickey"><br>
Last name: 
<input type="text" name="LastName" value="Mouse"><br>
<input type="submit" value="Submit">
</form> 

</body>
</html>
6
  • 1
    Since you're not adding event as a parameter in submit function, this doesn't work in Firefox.
    – Stryner
    Jan 7, 2015 at 17:52
  • 1
    @Ninsly how do you add event as a parameter to submit function? Please post answer. Jan 7, 2015 at 17:54
  • @HenrikPetterson Simply change $("form").submit(function(){ to $("form").submit(function(event){
    – Stryner
    Jan 7, 2015 at 17:55
  • 1
    Wouldn't this prevent all form submissions? What about the first form submission that is actually wanted? Jan 7, 2015 at 17:56
  • 1
    Even if you add the event parameter this totally stops any form submission!
    – j08691
    Jan 7, 2015 at 17:56

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.