How to Create Live Voting System using Ajax and PHP

In this tutorial, we are going to create a simple voting system using PHP and jQuery AJAX. We will creating own Poll system (AJAX) for your projects with PHP. Polls, answers and results I going to keep in single SQL table. You may also like Live Search in php with Ajax and Mysql .

HTML and jQuery Code

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">
            function postvote()
            {
                var all = document.getElementsByTagName("input");
                for (var i = 0; i < all.length; i++)
                {
                    if (all[i].type == "radio" && all[i].checked)
                    {
                        var vote = all[i].value;
                    }
                }

                if (vote)
                {
                    $.ajax({
                        type: 'post',
                        url: 'insertvote.php',
                        data: {
                            vote_val: vote
                        },
                        success: function (response) {
                            $('#vote_status').html(response);
                        }
                    });
                } 
                else
                {
                    $('#vote_status').html("Please Select Language");
                }
                return false;
            }
        </script>

    </head>
    <body>
        <form method="POST" onsubmit="return postvote();">
            <p>Which Is A Best Language?</p>
            PHP <input type="radio" name="yourvote" value="PHP">
            jQuery <input type="radio" name="yourvote" value="jQuery">
            ASP.Net <input type="radio" name="yourvote" value="ASP.Net">
            <input type="submit" name="submit_form" value="Vote">
        </form>
        <p id="vote_status"></p>

    </body>
</html>

PHP Code (insertvote.php)

<?php
define('DB_SERVER', "localhost");
define('DB_USER', "root");
define('DB_PASS', "");
define('DB_DATABASE', "whatsappdwld_db");
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);

if (isset($_POST['vote_val'])) {
    $userip = $_SERVER['REMOTE_ADDR'];
    $checkip = " SELECT user_ip FROM user_vote WHERE user_ip= '".$userip."' ";
    $query = mysqli_query($con, $checkip);
    if (mysqli_num_rows($query) > 0) 
    {
        echo "You Already Post Your Vote";
    } 
    else 
    {
        $vote = $_POST['vote_val'];
        $insertdata = " INSERT INTO user_vote (user_id, user_vote)VALUES( '$userip','$vote' ) ";
        mysqli_query($con,$insertdata);
        echo "You Vote Is Successfully Inserted";
    }
    exit();
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *