wordpress/php: create an upvote button that does not refresh page

Beginning developer here, making a website using wordpress as a platform. I would like the user to be able to click an upvote button and upvote a post without refreshing the page. I figure I should probably use javascript to highlight the button once clicked as well as change the vote number. However, I am having trouble figuring out how to run a php script (to update the database) without refreshing the page.

Thanks in advance,

Related posts

Leave a Reply

1 comment

  1. sample upvote php for posts add this to your functions file….

    add_action('wp_ajax_upvote', 'upvote');
    add_action('wp_ajax_nopriv_upvote', 'upvote');
    
    function upvote() {
       $postid= $_POST['id'];
       $direction = $_POST['direction'];
       $votes= get_post_meta($postid, '_votes', true);
    
       if($direction='down') {
          $votes--;
       } else {
          $votes++;
       }
    
       update_post_meta($postid, '_votes', $votes);
       echo $votes;
       exit();
    }
    

    The above needs security like any form submit of $_POST variables. Dont leave these out in your code!!

    jQuery Code

    jQuery(document).ready(function($){
        $('.arrow').click(function(){ //if your upvote has class arrow?
            //you need someway of passing postid to here!
            //if you want up / downvote -- logic needed here, if not remove direction from below!
    
            $.ajax({
               type: "POST",
               url: "/wp-admin/admin-ajax.php",
    
               data: {
                  action: 'upvote',
                  id: id,
                  direction: direction //remove if not needed
               },
    
               success: function (output) { //do something with returned data
    
                  console.log(output);
                  jQuery('#postupvote').text(output); //write to correct id - maybe use postid in the id of the vote count on the page e.g. id="vote23" jQuery('#vote'+postid)
            }
    
    
            });
        });
    
    })
    

    google wordpress ajax for more information