Prevent Data Resubmission On Page refresh

UPDATED FOR CLARIFICATION

I’ve got this rating plugin that keeps submitting & duplicating the rating data on page refresh. When a user wants to add a rating, they have to click a button that takes them to “mysite.com/?review=true”

After they submit their review, the browser stays on “mysite.com/?review=true”

Upon refreshing the browser, the review is resubmitted, causing duplicate entries.

How can I check against duplicates in the database and stop this?

http://pastebin.com/c6wPGRD5 – class.php

http://pastebin.com/tz4PvWtS – form submit.php

http://pastebin.com/9ebCxpMZ – plugin.php

Solutions Collecting From Web of "Prevent Data Resubmission On Page refresh"

To prevent multiple button clicks, you can use JavaScript to disable the button.

jQuery('#review_member_button').on('click', function(evt) {
    jQuery(this).attr('disabled', 'disabled');
});

On the WordPress end, you can set a unique key for the form every time it’s generated and check to see if a form with that key has been resubmitted. I would recommend setting a transient, since they’re temporary and easily cached with a plugin like Batcache.

When you build your form:

<?php
    $token_id = md5( uniqid( "", true ) );
?>

<form>
    ... Other form stuff
    <input type="hidden" name="token" value="<?php echo $token_id; ?>" />
</form>

Then, when you process your form:

<?php
$token_id = stripslashes( $_POST['token'] );

// If the transient exists, this is a duplicate entry. So don't do anything
if ( ! get_transient( 'token_' . $token_id ) ) {
    return;
}

// If the transient doesn't exist, set it so we don't process the form twice
set_transient( 'token_' . $token_id, 'dummy-content', 60 ); // Cache for 1 minute

// ... do your other processing

submitting & duplicating the rating data on page refresh.

If it’s only an issue for page refreshes redirect the user after form submission. This will prevent re-submission because the browsers current request wasn’t the form submission. Quick example: in your form handler…

<?php
// your form handler someplace

// save the rating data.

wp_redirect($page_they_came_from, 303);
exit;

If you need to prevent users from voting multiple times, set a cookie at the tail end of your form handler (then redirect, see above).

<?php
// you form handler someplace

// save rating data

$voted = isset($_COOKIE['_wp_voted']) ? explode(',' $_COOKIE['_wp_voted']) : array();

if(!in_array($the_item_for_voting, $voted))
{
    // save votes here.

    $voted[] = $the_item_for_voting;
}

setcookie(
    '_wp_voted',
    implode(',', $voted),
    time() + (60 * 60 *24), // one day
    '/', // the whole site
    COOKIE_DOMAIN, // this is set by WP, or in your wp-config.php
    false,
    true
);

wp_redirect($page_they_came_from, 303);
exit;