0

I can´t get the correct output for the corresponding div on each post. How can I pass in the corresponding post id when clicking the button? This is an AJAX-request via jQuery.

template.php

          $votes = get_post_meta($post->ID, "votes", true);
          $votes = ($votes == "") ? 0 : $votes;


          echo '<div id="vote_counter">'. $votes.'</div><br>';

voteme.js

 jQuery(document).ready( function() {

 jQuery(".user_vote").on('click', function(event) {
    event.preventDefault();
    post_id = $(this).attr("data-post_id");
    nonce = $(this).attr("data-nonce");

 jQuery.ajax({
     type : "post",
     dataType : "json",
     url : myAjax.ajaxurl,
     data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
     success: function(response) {
        if(response.type == "success") {
           jQuery("#vote_counter").html(response.vote_count);
        }
        else {
           alert("Your vote could not be added");
        }


     }

   });   

 });
   return false; 
});

functions.php

add_action( 'init', 'my_script_enqueuer' );

function my_script_enqueuer() {
   wp_register_script( "my_voter_script", get_stylesheet_directory_uri() .'/js/voteme.js', array('jquery') );
   wp_localize_script( 'my_voter_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));        

   wp_enqueue_script( 'jquery' );
   wp_enqueue_script( 'my_voter_script' );

}

add_action("wp_ajax_my_user_vote", "my_user_vote");
add_action("wp_ajax_nopriv_my_user_vote", "my_must_login");

function my_user_vote() {

   if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
      exit("No naughty business please");
   }   

   $vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
   $vote_count = ($vote_count == '') ? 0 : $vote_count;
   $new_vote_count = $vote_count + 1;

   $vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);

   if($vote === false) {
      $result['type'] = "error";
      $result['vote_count'] = $vote_count;
   }
   else {
      $result['type'] = "success";
      $result['vote_count'] = $new_vote_count;
   }

   if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
      $result = json_encode($result);
      echo $result;
   }
   else {
      header("Location: ".$_SERVER["HTTP_REFERER"]);
   }

   die();

}

function my_must_login() {
   echo "You must log in to vote";
   die();
}
5
  • 1
    What's the failure or specific question to be answered?
    – jdm2112
    Commented Mar 15, 2018 at 20:26
  • The output in the div updates the first div in the first post. I am trying to output the vote from the current id to the corresponding post. echo '<div id="vote_counter">'. $votes.'</div><br>';
    – tc2049
    Commented Mar 15, 2018 at 20:41
  • The question is: How do I output the value to the corresponding div? I have tried looping in php but I think that jQuery will select the element for me.
    – tc2049
    Commented Mar 16, 2018 at 8:08
  • I know I cant access the same id in jQuery but change to classes to access them all. But I think the solution is to loop through all the corresponding post ids in PHP and output accordingly.
    – tc2049
    Commented Mar 16, 2018 at 9:39
  • I have changed the id in the div to a class but it outputs, as expected, to all divs. My objective is to output according to data-post_id which I have also added to the div. But since it is one div with one class it doesn't output accordingly. How do I achieve this? Any suggestions would be appreciated since I have been stuck for days.
    – tc2049
    Commented Mar 19, 2018 at 11:13

1 Answer 1

1

[EDIT] Provided better replacements.

Try this:

In template.php, replace:

echo '<div id="vote_counter">'. $votes.'</div><br>';

..with:

echo '<div id="vote_counter-' . $post->ID . '" class="vote_counter">'. $votes.'</div><br>';

In voteme.js, replace:

jQuery("#vote_counter").html(response.vote_count);

..with:

jQuery("#vote_counter-" + post_id).html(response.vote_count);

You should also declare post_id and nonce as local variables; i.e.:

var post_id = $(this).attr("data-post_id"),
  nonce = $(this).attr("data-nonce");

Hope that helps.

5
  • 1
    I'd swap the id and class on the <div>: echo '<div class="vote_counter" id="vote_counter-' . $post->ID . '">'{...} . IIRC, ids should be unique on the page, but classes can be re-used.
    – Pat J
    Commented Mar 20, 2018 at 18:38
  • 1
    @PatJ, yes you're right. I'd actually do the same, but perhaps I temporarily forgot that.. or was a bit confused. Thanks! =)
    – Sally CJ
    Commented Mar 21, 2018 at 6:22
  • 1
    That did the trick! I tried several outputs but nothing worked. Thanks again! This is very useful!
    – tc2049
    Commented Mar 21, 2018 at 8:52
  • @tc2049 You're welcome! And don't forget to upvote or accept the answer.. =)
    – Sally CJ
    Commented Mar 21, 2018 at 8:59
  • 1
    Done! I am a newbie here but I will upvote it when I have 15 in rep.
    – tc2049
    Commented Mar 21, 2018 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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