Monday, May 24, 2010

10:14 PM
1

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");
mysql_select_db("polls");
$query=mysql_query("SELECT id, ques FROM questions ORDER BY id DESC LIMIT 1");
while($row=mysql_fetch_assoc($query)){
//display question
echo "<p class=\"pollques\" >".$row["ques"]."</p>";
$poll_id=$row["id"];
}
//display options with radio buttons
$query=mysql_query("SELECT id, value FROM options WHERE ques_id=$poll_id");
if(mysql_num_rows($query)){
echo '<div id="formcontainer" ><form method="post" id="pollform" action="'.$_SERVER['PHP_SELF'].'" >';
echo '<input type="hidden" name="pollid" value="'.$poll_id.'" />';
while($row=mysql_fetch_assoc($query)){
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"])."'");
if(mysql_num_rows($query)){
$query="INSERT INTO votes(option_id, voted_on, ip) VALUES('".$_POST["poll"]."', '".date('Y-m-d H:i:s')."', '".$_SERVER['REMOTE_ADDR']."')";
if(mysql_query($query))
{
//Vote added to database
setcookie("voted".$_POST['pollid'], 'yes', time()+86400*300);
}
else
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 thevotes 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')");
while($row=mysql_fetch_assoc($query))
$total=$row['totalvotes'];
$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");
while($row=mysql_fetch_assoc($query)){
$percent=round(($row['votes']*100)/$total);
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 BYquery 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" >
</div>
<p id="loader" >Loading...</p>
</div>

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');
loader.fadeIn();
//Load the poll form
$.get('poll.php', '', function(data, status){
pollcontainer.html(data);
animateResults(pollcontainer);
pollcontainer.find('#viewresult').click(function(){
//if user wants to see result
loader.fadeIn();
$.get('poll.php', 'result=1', function(data,status){
pollcontainer.fadeOut(1000, function(){
$(this).html(data);
animateResults(this);
});
loader.fadeOut();
});
//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
('#pollform').submit(function(){
var selected_val=$(this).find('input[name=poll]:checked').val();
if(selected_val!=''){
//post data only if a value is selected
loader.fadeIn();
$.post('poll.php', $(this).serialize(), function(data, status){
$('#formcontainer').fadeOut(100, function(){
$(this).html(data);
animateResults(this);
loader.fadeOut();
});
});
}
//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.





1 comments:

Muhammad Azeem said...

This is a nice article..
Its easy to understand ..
And this article is using to learn something about it..

c#, dot.net, php tutorial, Ms sql server

Thanks a lot..!
002s