AJAX User Poll Using jQuery and PHP

Posted in jQuery PHP

AJAX User Poll Using jQuery, 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.
Database Structure
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;

Download the complete source code and try it out for yourself.

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.



Subscribe to Full RSS Feed

RSS FeedIf you found this article useful, then consider subscribing to our RSS Feed or e-mail updates to stay updated with latest Web Design/ Development articles. You can also follow @webdevplus on twitter for latest updates.

23 Responses (Add Your Comment)

  1. Arvid Slump says:

    I advise against using this untill theres errorhandling installed. Its completely lacking it at this point. You cant ever assume things go how you want them to go!

  2. nice plugin but cant load the file, it missing. please upload it.

  3. webdev says:

    This is a great plugin.
    I wanted help to add Vote link on the view results, so that users can go back to the poll form.
    Kindly help as Im new to ajax.

    Thanks in advance

    • Satbir says:

      there was an extra comma in line 54 of index.html that caused the problem, i have removed it and updated the source code file. It is working now. Thanks for reporting.

  4. First at all, thank you! Nice and clean coded plugin with animation effect. Is this only cookie based?

    if($_GET["result"]==1 || $_COOKIE["voted".$poll_id]==’yes’)
    //if already voted or asked for result
    IF_EXIST -> showresults($poll_id);
    //display options with radio buttons


  5. Mark says:

    Satbir, thanks for this script!

    Unfortunately there is a small error. When you don’t select an option and submit an empty vote, the whole poll gets reloaded and you will see the question twice.

    When you submit an empty vote for the second time, poll.php gets displayed instead of index.html.

    Do you have a solution for this problem?

  6. jo says:


    May I suggest to run the sql commands directly from the poll.php? Is it possible to improve? How can I achieve this?


  7. Ken says:


    Nice plugin! How can I use it with jQuery.1.2.6-pack.js?

    Thank you!

  8. Leandro says:

    first, thanks for share the code, second, excuseme,but where do you locate the update code excatly?? :S

  9. Leandro says:

    i’m sorry it’s Monday, too early, i wrote a stupid question before…

  10. mubarak says:

    Hi good work, if i delete the records in the table votes, i am not geting the container with questions and Options, instead i am getting only Question..

    Can you help me pls

  11. padipaws says:

    i love this post. keep going!

Comments are closed for this post.