phpmysqlajaxonclickvote

Add +1 Vote to MYSQL database on click


So I'm making a quiz game that will show the percentage of people that agreed with you when an option is clicked. On click, results of previous players are displayed and your vote will be added to a database.

I have been trying to figure this out for quite some time now and after reading numerous posts and watching a lot of videos, it seems as though a combination of ajax and php is the way to go, I just can't seem to get it to play nice.

Here's what I've got. (With non-essential stuff removed to make it clearer.)

HTML

<div id="option1"></div>

JQUERY

$(document).ready(function() { 
$('#option1').click(function() {
    var request = $.ajax({
        type: "POST",
        url: "clickvote.php",

        });
    }); 
});

I feel as though this is the problem. It seems as though jquery isn't actually calling the php file, am i missing something here, do i need to insert some form of data at this point rather than in the php?

PHP (clickvote.php)

<?php

include ('db_connect.php'); 
include ('getpageid.php');


$sql = "UPDATE questions SET votes1 = (votes1 + 1) WHERE id = {$pageid}";

mysqli_query($db,$sql);


?>

This PHP adds the vote and runs if I include it at top of the question page, however it adds the vote every time the page is loaded, not when option 1 is clicked, like i want it.

Let me know if you need any additional info.

Any help would be really appreciated!

Daniel


Solution

  • First make sure of your php script path. Use your browser network it should return a success.

    Try submitting the page id from the client side

    $(document).ready(function() { 
    $('#option1').on('click', (function() {
        var request = $.ajax({
            type: "POST",
            url: "clickvote.php",
            data: {"page" : <?php echo $page_id ?>}
            });
        }); 
    });
    

    And then

    <?php
    
    include ('db_connect.php'); 
    include ('getpageid.php');
    $pageId = filter_input(INPUT_POST, 'page');
    
        $sql = "UPDATE questions SET votes1 = (votes1 + 1) WHERE id = ?";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param($pageId);
    $stmt->execute();  
    
    ?>
    

    Add prepared statements to make your query secure.