The poll system used by the site administrator to get the users views on the topic or a product.
The user can select an option and submit a vote.
The overall percentage of the option will display after submit.
In this tutorial, I show how you can create a poll system with jQuery AJAX.
Contents
1. Table structure
I am using three tables –
poll – Store the voting question
CREATE TABLE `poll` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `question` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
poll_options – Store the voting question options
CREATE TABLE `poll_options` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `pollid` int(11) NOT NULL, `name` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
poll_result – Store the user voting on a poll option
CREATE TABLE `poll_result` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `userid` id(11) NOT NULL, `pollid` id(11) NOT NULL, `poll_option_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2. Configuration
Create a new config.php
to define database connection.
Completed Code
<?php session_start(); $host = "localhost"; /* Host name */ $user = "root"; /* User */ $password = ""; /* Password */ $dbname = "tutorial"; /* Database name */ $con = mysqli_connect($host, $user, $password,$dbname); // Check connection if (!$con) { die("Connection failed: " . mysqli_connect_error()); }
3. HTML
Create a <div id='poll'>
container.
With jQuery display voting form or result in the <div id='poll'>
.
Completed Code
<div class='container'> <!-- Poll --> <div id='poll'></div> </div>
4. CSS
#poll ul{ list-style: none; padding-left: 0; } .poll_option{ margin-bottom: 5px; } .poll_optionname{ width: 160px; padding: 5px; display: inline-block; color: white; } .poll_votes{ width: 80px; padding: 5px; display: inline-block; background-color: gainsboro; text-align: center; }
5. PHP
Create a new vote.php
file to handle AJAX requests.
From this file handle two requests –
I fixed the pollid=1
and userid=12
.
1. $request == 1 ( Return voting form/ Voting result )
Check if a user already submitted a vote or not.
If submitted a vote
Select question from poll
table and options from poll_options
on the basis of $pollid
.
Create an unordered list with a radio button where use $poll_option_id
in the value
attribute.
A button to submit vote where define onclick='saveVote()'
.
If not submitted a vote
Count the total number of votes on the poll from poll_result
and fetch poll question from the poll
table.
Count total votes on the poll options using LEFT JOIN
between poll_options
and poll_result
tables.
Loop on the fetch records and calculate the percentage.
Create an unordered list that has option name and percentage.
Return the $html
.
2. $request == 2 ( Save user vote )
Check if a user already voted or not on poll_result
table. If not then insert a record in the poll_options
table and return 1
otherwise 0
.
Completed Code
<?php include "config.php"; $pollid = 1; // Poll id $userid = 11; // User id $request = $_POST['request']; // Display Vote form / Poll result if($request == 1){ // Check user already voted $userpoll_sql = "SELECT * FROM poll_result WHERE pollid=".$pollid." and userid=".$userid; $userpollData = mysqli_query($con,$userpoll_sql); if(mysqli_num_rows($userpollData) == 0){ ## Display Poll options // Fetch Poll question $pollData = mysqli_query($con,"SELECT * FROM poll WHERE id=".$pollid); while($pollrow = mysqli_fetch_assoc($pollData)){ $question = $pollrow['question']; // Poll Question and options $polloptionData = mysqli_query($con,"SELECT * FROM poll_options WHERE pollid=".$pollid); $html = "<div> <p>".$question."</p> <ul>"; while($polloptionrow = mysqli_fetch_assoc($polloptionData)){ $pollid = $polloptionrow['id']; $pollname = $polloptionrow['name']; $html .= "<li> <input type='radio' value='".$pollid."' name='poll'>".$pollname." </li>"; } $html .= "</ul>"; } $html .= ' <input type="button" value="Vote" id="but_vote" onclick="saveVote();"> </div>'; }else{ ## Display Poll result // Count total votes $pollresultData = mysqli_query($con,"SELECT count(*) as allcount FROM poll_result WHERE pollid=".$pollid); $pollresultData_row = mysqli_fetch_assoc($pollresultData); $totalVotes = $pollresultData_row['allcount']; // Color codes $colors_arr = array("#28f474","#008080","#e3242b","#ffb067"); // Question $pollData = mysqli_query($con,"SELECT question FROM poll WHERE id=".$pollid); $rowpollData = mysqli_fetch_assoc($pollData); $question = $rowpollData['question']; // Fetch poll option votes $pollresult_SQL = "SELECT po.id,po.name,COUNT(pr.poll_option_id) as votes FROM poll_options po LEFT JOIN poll_result pr ON po.id=pr.poll_option_id WHERE po.pollid=".$pollid." GROUP BY po.id"; $pollresultData = mysqli_query($con,$pollresult_SQL); // Display poll option and percentage $html = "<div> <h2>Result</h2> <p>".$question."</p> <ul>"; $count = 0; while($row = mysqli_fetch_assoc($pollresultData)){ $pollid = $row['id']; $pollname = $row['name']; $poll_vote = $row['votes']; // Get color code $backgroundColor = $colors_arr[$count]; $count++; if($count >= count($colors_arr)){ $count = 0; } // Find percentage $percentage = ($poll_vote/$totalVotes)*100; $html .= "<li> <div class='poll_option'> <div class='poll_optionname' style='background-color: ".$backgroundColor."' >".$pollname."</div> <div class='poll_votes' >".round($percentage,2) ." %</div> </div> </li>"; } $html .= '</ul> </div>'; } echo $html; exit; } // Save vote if($request == 2){ $poll_option_id= $_POST['poll']; $response = 0; // Check user vote $userpoll_sql = "SELECT * FROM poll_result WHERE pollid=".$pollid." and userid=".$userid; $userpollData = mysqli_query($con,$userpoll_sql); if(mysqli_num_rows($userpollData) == 0){ // Insert user vote mysqli_query($con,"INSERT INTO poll_result(pollid,poll_option_id,userid) VALUES(".$pollid.",".$poll_option_id.",".$userid.")"); $response = 1; } echo $response; exit; }
6. jQuery
Create two functions –
- checkPoll() – Send an AJAX request to check the user has voted or not.
Add the response to <div id='poll'>
.
- saveVote() – This function call on the vote button click.
Get the checked radio button value and send an AJAX request to save the vote where pass the checked radio button value as data
.
If response == 1
then call checkPoll()
function to display the poll result.
Completed Code
$(document).ready(function(){ // Check user vote checkPoll(); }); // Check user vote function checkPoll(){ $.ajax({ url: 'vote.php', type: 'post', data: {request: 1}, success: function(response){ $('#poll').html(response); } }); } // Save user poll function saveVote(){ var checkedPoll = $("#poll input[name='poll']:checked").val(); if(checkedPoll != undefined){ $.ajax({ url: 'vote.php', type: 'post', data: {request: 2,poll: checkedPoll}, success: function(response){ if(response == 1){ checkPoll(); } } }); } }
7. Demo
Select an option and click on the vote button.
8. Conclusion
I fixed the userid
and pollid
values in the example which you can update while implementing the script.