How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

user701510 picture user701510 · Jun 12, 2011 · Viewed 313.3k times · Source

I have a simple form that submits text to my SQL table. The problem is that after the user submits the text, they can refresh the page and the data gets submitted again without filling the form again. I could redirect the user to another page after the text is submitted, but I want users to stay on the same page.

I remember reading something about giving each user a unique session id and comparing it with another value which solved the problem I am having but I forgot where it is.

Answer

dtbaker picture dtbaker · Aug 13, 2017

I would also like to point out that you can use a javascript approach, window.history.replaceState to prevent a resubmit on refresh and back button.

<script>
    if ( window.history.replaceState ) {
        window.history.replaceState( null, null, window.location.href );
    }
</script>

Proof of concept here: https://dtbaker.net/files/prevent-post-resubmit.php

I would still recommend a Post/Redirect/Get approach, but this is a novel JS solution.