I’m trying to create a voting system where user can click to vote! But it will collect their Facebook user id so that one person can’t submit more than one vote on a post!
Here is my code which I’m using –

$(".vote i").on("click", function() {
    $this = $(this);

    var votePostID = $(this).closest(".scholarship-card").attr("id");
    postID = votePostID;

    FB.getLoginStatus(function(response) {
        if (response.status === 'connected') {
            $this.closest(".vote").find("span").html("vote submitted!");
            submitVote(postID);
            FBAPI();
        } else {
            showLoginPopup();
        }
    });

});

function submitVote(post_id) {
    $.ajax({
        url: "voting.php",
        type: "POST",
        data: {postID: post_id, fbID: fb_id},
        beforeSend: function() {
            console.log("sending...");
        },
        success: function (data) {
            console.log("done...");
            console.log(data);
            console.log(data.vote);
        }
    });
}

And here is the PHP standalone file which is being called on ajax request –

<?php

    $path = $_SERVER['DOCUMENT_ROOT'];

    include_once $path . '/wp-config.php';
    include_once $path . '/wp-load.php';
    include_once $path . '/wp-includes/wp-db.php';
    include_once $path . '/wp-includes/pluggable.php';

    $postID = $_POST["postID"];
    $fbID = $_POST["fbID"];

    $response = array();


    $response["vote"] = "THIS IS WORKING...";

    $fbID_fetch = $wpdb->get_var("SELECT postID FROM scholarship_votes_uid WHERE uid=$uid");

    $response["fBID_fetch"] = $fbID_fetch;

    if ( $fbID_fetch === null ) {
        $wpdb->query("INSERT INTO scholarship_votes_uid(uid, postID) VALUE ($uid, $postID)");
        /*$wpdb->insert('scholarship_votes_uid', 
                        array( 
                            'uid' => $fbID,
                            'postID' => $postID
                        ), 
                        array( 
                            '%d', 
                            '%d' 
        ));*/
        $wpdb->insert('scholarship_votes_count', 
                        array( 
                            'postID' => $postID, 
                            'voteCount' => 0 
                        ), 
                        array( 
                            '%d', 
                            '%d' 
        ));

        $wpdb->query("UPDATE scholarship_votes_count SET voteCount=voteCount+1 WHERE postID=$postID");

    } else {
        $response["error"] = "Already Voted!";
    }


    echo json_encode($response);

?>

Please help me to find the solution. I’m just dying to fix this voting system!

Read more here: Unable to insert data in databse when trying with $wpdb class


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: