Ajax Comment Upvotes - Votes don't always register

by J. Stockland   Last Updated August 14, 2019 15:08 PM

I'm trying to create a simple ajax-based comment upvoting system for Wordpress. I've managed to build most of it, but now it seems that most of the time the upvotes don't register. They do register sometimes (but only maximum of 2, even though I did not implement a limit), and the Ajax call gets a successful response (so the PHP function is executed I guess).

Any ideas where I'm going wrong (this is my first Ajax project)?

PHP function:

add_action( 'wp_ajax_comment_meta_update_vote', 'comment_meta_update_vote' );

function comment_meta_update_vote( ) {
    check_ajax_referer( 'upvote_nonce' );

    $comment_id = $_POST['comment_id'];
    $vote_score = get_comment_meta($comment_id , 'vote', true);
    ++$vote_score;
    update_comment_meta($comment_id , 'vote', $vote_score, true );


      $response['type'] = 'success';
      $response = json_encode( $response );
      echo $response;
    die(); 
}

Javascript Function:

function updateVote( comment_id ){

    jQuery(function($) {
      $.ajax({
      type : 'post',
      dataType : 'json',
      url : upvote_ajax.ajax_url,
      data : {
        action: 'comment_meta_update_vote',
        comment_id: comment_id,
        _ajax_nonce: upvote_ajax.nonce
      },
      success: function( response ) {
         if( 'success' == response.type ) {
            // console.log('success');
         }
         else {
           // alert( 'Something went wrong, try logging in!' );
         }
      }
    }) })};


Related Questions




Path to external JS File

Updated January 02, 2017 08:03 AM