0

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!' );
         }
      }
    }) })};
  • Is there any error in the browser console? – Makiomar Aug 14 at 14:59
  • No errors in the browser console... – J. Stockland Aug 14 at 15:08
  • Update: Found the error: update_comment_meta($comment_id , 'vote', $vote_score, true ); should not have a TRUE parameter. Removing that made it work again. – J. Stockland Aug 14 at 15:16
0

Please try this and inform me what you got in the console. and sure console.log the type

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++;
$updated = update_comment_meta($comment_id , 'vote', $vote_score );

  if($updated){
    $msg = 'success';
  }else{
    $msg = 'failed';
  }
  $response = array('type' => $msg);
  wp_json_encode( $response );

die(); 
}
  • Thanks. I think I found the error just before you posted: Found update_comment_meta($comment_id , 'vote', $vote_score, true ); should not have a TRUE parameter. Removing that made it work again. – J. Stockland Aug 14 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.