To verify nonces in Ajax requests, check_ajax_referrer()
should be used instead of wp_verify_nonce()
:
Crete the nonce:
$nonce = wp_create_nonce( 'vote-nonce-' . get_the_ID() );
Include it in JavaScript:
jQuery(document).ready(function(){
jQuery(".post-voting").click(function(){
vote_nonce = <?php echo $nonce; ?>
vote_id = jQuery(this).data('vote-id');
jQuery.post(
vote_ajax.url,
{
action: 'submit_vote',
vote_id: vote_id,
vote_nonce: vote_nonce
},
function( data ) {
alert( jQuery.parseJSON(data) );
}
);
});
});
Check in the ajax callback:
add_action( 'wp_ajax_submit_vote', 'submit_vote' );
function submit_vote() {
$vote_id = intval( $_POST['vote_id'] );
$vote_nonce_name="vote-nonce-" . $vote_id;
// By default, check_ajax_referer dies if nonce can not been verified
if( ! check_ajax_referer( $vote_nonce_name, 'vote_nonce', false ) ) {
wp_send_json_error();
} else {
wp_send_json_success();
}
}