AJAX User Poll Using jQuery and PHP

Today, we’ll be creating a nice user poll script using jQuery and PHP utilizing AJAX and animation effects of jQuery to spice up the user interface and provide a rich user experience. Let’s get started.

Set up the database

For storing poll questions, options and votes, we’ll be using a MySQL database. Here is the database structure required.

There are three tables:

  • questions table stores the poll questions.
  • options table stores the options of a particular question.
  • votes table stores information about each vote cast by the user.

The required SQL code with sample data is provided in source code(below).

The PHP Code

Displaying the poll form

We’ll display the most recent poll question from the database and allow the user to vote for it. Here’s the required PHP code to generate poll form for latest poll question.

$conn=mysql_connect('localhost', 'root', 'password') or die("Can't connect to mysql host");
$query=mysql_query("SELECT id, ques FROM questions ORDER BY id DESC LIMIT 1");
	//display question
	echo "<p class=\"pollques\" >".$row["ques"]."</p>";
//display options with radio buttons
$query=mysql_query("SELECT id, value FROM options WHERE ques_id=$poll_id");
		echo '<div id="formcontainer" ><form method="post" id="pollform" action="'.$_SERVER['PHP_SELF'].'" >';
		echo '<input type="hidden" name="pollid" value="'.$poll_id.'" />';
			echo '<p><input type="radio" name="poll" value="'.$row['id'].'" id="option-'.$row['id'].'" /> 
			<label for="option-'.$row['id'].'" >'.$row['value'].'</label></p>';
		echo '<p><input type="submit"  value="Submit" /></p></form>';

Processing the Submitted Vote

When user selects an answer and submits the form, we add the information to the votes table about the option selected and also set a cookie in user’s browser to identify that he has voted for the poll.

$query=mysql_query("SELECT * FROM options WHERE id='".intval($_POST["poll"])."'");
	$query="INSERT INTO votes(option_id, voted_on, ip) VALUES('".$_POST["poll"]."', '".date('Y-m-d H:i:s')."', '".$_SERVER['REMOTE_ADDR']."')";
		//Vote added to database
		setcookie("voted".$_POST['pollid'], 'yes', time()+86400*300);				
		echo "There was some error processing the query: ".mysql_error();

In this case we first check to see if the answer to poll question has been provided and whether the user hasnot already voted(code omitted for simplicity) the selected option is there in database or not. Also here we are using intval() function to make sure only integer value for selected option passes through. After checking the information, the user vote is added to the votes table.

Displaying the Results

Once the user has voted, it’s time to display the results to him. We’ll be using the easy way out to display the result using CSS. Here’s the code for that.

$query=mysql_query("SELECT COUNT(*) as totalvotes FROM votes WHERE option_id IN(SELECT id FROM options WHERE ques_id='$poll_id')");
$query=mysql_query("SELECT options.id, options.value, COUNT(*) as votes FROM votes, options WHERE votes.option_id=options.id AND votes.option_id IN(SELECT id FROM options WHERE ques_id='$poll_id') GROUP BY votes.option_id");
	echo '<div class="option" ><p>'.$row['value'].' (<em>'.$percent.'%, '.$row['votes'].' votes</em>)</p>';
	echo '<div class="bar ';
	if($_POST['poll']==$row['id']) echo ' yourvote';
	echo '" style="width: '.$percent.'%; " ></div></div>';
echo '<p>Total Votes: '.$total.'</p>';

To display the results from the information we have in votes table, we will use a GROUP BY query to find out votes per option and then set the width of display bar based on percentage of votes each option received.

All the PHP code is in poll.php file.

HTML Structure

HTML structure is quite simple as jQuery will do the heavy lifting. We only need to define a container that will hold the poll form or display the results.

<div id="container" >
	<h1>User Poll</h1>
	<div id="pollcontainer" >
	<p id="loader" >Loading...</p>

The JavaScript Code

Loading the Poll Form

On page load, we will load and display the poll form to user and if user has already voted, then results will be displayed.

var loader=$('#loader');
	var pollcontainer=$('#pollcontainer');
	//Load the poll form
	$.get('poll.php', '', function(data, status){
			//if user wants to see result
			$.get('poll.php', 'result=1', function(data,status){
				pollcontainer.fadeOut(1000, function(){
			//prevent default behavior
			return false;

Processing User Vote

To process the user vote, we first check to see if user has selected one of the options and then post the form data to poll.php and then display the results to the user in a nice animated way using the function animateResults.

			var selected_val=$(this).find('input[name=poll]:checked').val();
				//post data only if a value is selected
				$.post('poll.php', $(this).serialize(), function(data, status){
					$('#formcontainer').fadeOut(100, function(){
			//prevent form default behavior
			return false;

Remember to set up database and tables using polls.sql file provided in source code and update database information in the poll.php file before trying out.

Note: In this tutorial, i have only covered the user interface part of the user poll script. You’ll have to code the user interface for creating new polls or manually have to add questions and options in the tables. The sample database file provided with the source code contains a sample poll question along with some sample data.