How to prevent form resubmission when page refreshes (F5/CTRL+R)
P粉151466081
2023-08-29 11:37:35
<p>I have a simple form that submits text to my SQL table. The problem is, after the user submits the text, they can refresh the page and submit the data again without filling out the form again. I can redirect the user to another page after submitting the text, but I want the user to stay on the same page. </p>
<p>I remember reading something about giving each user a unique session ID and comparing it to another value, which solved the problem I was having, but I forgot where it was. </p>
I also want to point out that you can use the JavaScript method
window.history.replaceState
to prevent resubmits on refresh and back buttons.Proof of concept: https://dtbaker.net/files/ Prevent-post-resubmit.php(Link is no longer valid)I still recommend the Post/Redirect/Get method, but this is a novel JS solution.
Use publish/redirect/get pattern. http://en.wikipedia.org/wiki/Post/Redirect/Get
On my website I will store the message in a cookie or session, redirect after posting, read the cookie/session, and then clear the value of that session or cookie variable.