Prevent form post data from re-submission.

By September 25, 2014 Code No Comments

How to prevent post data from a form re-submitting.

Here’s a little trick I picked up along the way to prevent form post data from re-submission. When a form is submitted the post data is set in the http header & if the user refreshes the page the data can be re-submitted.
OK, the browser warns the user that this is happening but not all users can be trusted to heed the warning & the danger of duplicate data be is present!

There are of course many ways to do this, but the one I am going o share with you today is using java script & php.

So let’s assume you already have your form and php script to get the $_POST data in place, which looks something like this:

What I decided to do is add an empty div to the page on successful interception on the $_POST data. So if all is well and your data is uploaded or whatever you intend to do with it, the code would look something like this:

Now we have to add a really simple bit of java script that will see if a class called “post-data-present” is in our page and if so do “location.reload();”. So out js would look like this:

Now when the page re-loads the $_POST data is gone and there is no fear of the data being re-submitted. Of course as with any js the user may have disabled js in the browser, but that is another argument.

Leave a Reply