Preventing Multiple Posts When Users Refresh

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

I’ve noticed recently that a handful of ABS readers have been posting duplicate comments — moreso than one should normally expect. I put myself in their shoes and posted a few test comments myself. It didn’t take long for me to notice that when I refreshed a page that I had just commented on, the prompt would come up asking me if I wanted to resend the data. Naturally, I clicked the first button I could to get rid of that hideous dialog box and, voila, a duplicate post.

Fortunately, we can use the PHP header function to get rid of that nasty form data and prevent duplicate posts.

<?php
//
// [DO SOMETHING WITH FORM DATA]
//
header("location: $_SERVER[PHP_SELF]"); exit();
?>

You can change the location to wherever you want. Effectively, we are using the header function to quietly redirect the user which, in turn, prevents refreshes and back buttons from resending the POST data.

If you enjoyed this article, please share it with a friend!

2 Responses to Preventing Multiple Posts When Users Refresh

  1. Sean O says:

    How would this work when the form is submitted by AJAX, like with the jQuery Form plugin?

  2. Cory LaViska says:

    You shouldn’t have to worry about this with an AJAX call, unless it’s being submitted to an IFRAME (i.e. for file uploads).

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>