Tutorial Details
- Programs: CSS, PHP, JavaScript
- Difficulty: Intermediate
- Completion Time: 1-2 hours
When you combine some neat functionality courtesy of PHP with the cleverness of jQuery you can produce some pretty cool results. In this tutorial we’ll create a poll using PHP and XHTML, then make use of some jQuery Ajax effects to eliminate the need for a page refresh, and to give it a nice little bit of animation.
This form will be processed by the PHP for now, and when we get the Javascript running, by jQuery. The PHP and Javascript are designed to pull the option ID from the value tag.
First, we need an array with the names and IDs of the poll options:
The flatfile package uses numbers for the column identifiers, so lets set some constants to convert those to names:
When the form is submitted, PHP needs to know what file to insert the results into and return, so we set another constant:
We need to include flatfile.php and initialize a database object:
The flat files are just text files stored in the data directory:
If we get a request with the poll parameter, it’s the static form, so we process it. If the request has a vote parameter in it, it’s a Ajax request. Otherwise, we just return the
The
The script tracks unique IPs to make sure you can only vote once, so we do a query to check whether it is in the DB:
If we don’t have a cookie and the IP query comes up empty, the client hasn’t voted yet, so we can just send the HTML file which contains the form. Otherwise, we just send the results:
These lines get the selected option’s ID, and set
We need to check whether the option is in the DB yet:
If it is in the DB (result not empty), we need to run an
Either way, we need to insert the IP into the DB, and set a cookie (expires in one year):
First, lets grab the HTML file and set
Next, we start the results HTML structure:
To create the results HTML we need to get all the rows (options) from the DB sorted by number of votes:
We also need the total votes to calculate percentages:
Next, we calculate the percentage of votes the current option has:
The HTML for the results will be a definition list (
Also, we should check if the current option is the one the client voted for, and change the color:
Here, we add a total vote count and close the html tags:
This is a regex that finds the poll-container
The last step in this function is to replace the poll form with the results using the regex, and return the result:
There are a few lines of code that are different from
The other two lines select the whole DB and return it as JSON:
This CSS styles the results returned by the PHP or Javascript.
First, some global variables. You should recognize the first three from the PHP.
Now we need a jQuery ready function which runs when the page loads:
Inside that function we register the handler for the vote button which will run
We also need to check if the results
If we have a cookie we should jump straight to generating the results because the user has already voted. To do that we need to get rid of the poll form, get the id from the cookie, grab the results from the PHP and pass them to
First, we need to prevent the default action (submitting the form):
Next, we get the ID from the currently selected option:
Now that we have the ID, we can process it. To start, we fade out the poll form, and setup an anonymous function as a callback that is run when the fade is complete. Animations don’t pause the script, so weird things happen if you don’t do it this way.
After it has faded out we can delete the form from the DOM using
In this case,
jQuery has some other shortcut functions, including
The last thing to do is set the cookie:
First, we set the percentage to the text of the element next to the bar which is the
Then we make sure the
HTML
Let’s get our<head>
set up:- <link href="style.css" rel="stylesheet" type="text/css" />
- <script src="jquery.js" type="text/javascript" charset="utf-8"></script>
- <script src="jquery.cookie.js" type="text/javascript" charset="utf-8"></script>
- <script src="poll.js" type="text/javascript" charset="utf-8"></script>
- style.css will hold the CSS markup.
- jquery.js is the base jQuery library.
- jquery.cookie.js is a plugin by Klaus Hartl to add cookie manipulation to jQuery.
- poll.js will have the Javascript that makes the poll dynamic.
- <div id="poll-container">
- <h3>Poll</h3>
- <form id='poll' action="poll.php" method="post" accept-charset="utf-8">
- <p>Pick your favorite Javascript framework:</p>
- <p><input type="radio" name="poll" value="opt1" id="opt1" /><label for='opt1'> jQuery</label><br />
- <input type="radio" name="poll" value="opt2" id="opt2" /><label for='opt2'> Ext JS</label><br />
- <input type="radio" name="poll" value="opt3" id="opt3" /><label for='opt3'> Dojo</label><br />
- <input type="radio" name="poll" value="opt4" id="opt4" /><label for='opt4'> Prototype</label><br />
- <input type="radio" name="poll" value="opt5" id="opt5" /><label for='opt5'> YUI</label><br />
- <input type="radio" name="poll" value="opt6" id="opt6" /><label for='opt6'> mootools</label><br /><br />
- <input type="submit" value="Vote →" /></p>
- </form>
- </div>
is just a HTML entity encoded space, and →
is an arrow: →.PHP
Introduction
If Javascript is disabled, the PHP will:- Take GET/POST requests from the form
- Set/check a cookie
- Make sure the request is from a unique IP
- Store the vote in a flat file DB
- Return the results included with a HTML file
- Take GET/POST requests from the Javascript
- Make sure the request is from a unique IP
- Store the vote in a flat file DB
- Return the results as JSON
First, we need an array with the names and IDs of the poll options:
- <?php
- $options[1] = 'jQuery';
- $options[2] = 'Ext JS';
- $options[3] = 'Dojo';
- $options[4] = 'Prototype';
- $options[5] = 'YUI';
- $options[6] = 'mootools';
- define('OPT_ID', 0);
- define('OPT_TITLE', 1);
- define('OPT_VOTES', 2);
- define('HTML_FILE', 'index.html');
- require_once('flatfile.php');
- $db = new Flatfile();
- $db->datadir = 'data/';
- define('VOTE_DB', 'votes.txt');
- define('IP_DB', 'ips.txt');
HTML_FILE
.- if ($_GET['poll'] || $_POST['poll']) {
- poll_submit();
- }
- else if ($_GET['vote'] || $_POST['vote']) {
- poll_ajax();
- }
- else {
- poll_default();
- }
poll_default()
- function poll_default() {
- global $db;
- $ip_result = $db->selectUnique(IP_DB, 0, $_SERVER['REMOTE_ADDR']);
- if (!isset($_COOKIE['vote_id']) && empty($ip_result)) {
- print file_get_contents(HTML_FILE);
- }
- else {
- poll_return_results($_COOKIE['vote_id']);
- }
- }
poll_default()
processes requests directly to the script with no valid GET/POST requests.The
global
line makes the $db
object available in the function’s scope.The script tracks unique IPs to make sure you can only vote once, so we do a query to check whether it is in the DB:
- $ip_result = $db->selectUnique(IP_DB, 0, $_SERVER['REMOTE_ADDR']);
- if (!isset($_COOKIE['vote_id']) && empty($ip_result)) {
- print file_get_contents(HTML_FILE);
- }
- else {
- poll_return_results($_COOKIE['vote_id']);
- }
poll_submit()
- function poll_submit() {
- global $db;
- global $options;
- $id = $_GET['poll'] || $_POST['poll'];
- $id = str_replace("opt", '', $id);
- $ip_result = $db->selectUnique(IP_DB, 0, $_SERVER['REMOTE_ADDR']);
- if (!isset($_COOKIE['vote_id']) && empty($ip_result)) {
- $row = $db->selectUnique(VOTE_DB, OPT_ID, $id);
- if (!empty($row)) {
- $ip[0] = $_SERVER['REMOTE_ADDR'];
- $db->insert(IP_DB, $ip);
- setcookie("vote_id", $id, time()+31556926);
- $new_votes = $row[OPT_VOTES]+1;
- $db->updateSetWhere(VOTE_DB, array(OPT_VOTES => $new_votes), new SimpleWhereClause(OPT_ID, '=', $id));
- poll_return_results($id);
- }
- else if ($options[$id]) {
- $ip[0] = $_SERVER['REMOTE_ADDR'];
- $db->insert(IP_DB, $ip);
- setcookie("vote_id", $id, time()+31556926);
- $new_row[OPT_ID] = $id;
- $new_row[OPT_TITLE] = $options[$id];
- $new_row[OPT_VOTES] = 1;
- $db->insert(VOTE_DB, $new_row);
- poll_return_results($id);
- }
- }
- else {
- poll_return_results($id);
- }
- }
poll_submit()
takes the form submission, checks if the client has already voted, and then updates the DB with the vote.These lines get the selected option’s ID, and set
$id
to it:- $id = $_GET['poll'] || $_POST['poll'];
- $id = str_replace("opt", '', $id);
- $row = $db->selectUnique(VOTE_DB, OPT_ID, $id);
updateSetWhere()
. If it isn’t we need to do an insert()
:- if (!empty($row)) {
- $new_votes = $row[OPT_VOTES]+1;
- $db->updateSetWhere(VOTE_DB, array(OPT_VOTES => $new_votes), new SimpleWhereClause(OPT_ID, '=', $id));
- poll_return_results($id);
- }
- else if ($options[$id]) {
- $new_row[OPT_ID] = $id;
- $new_row[OPT_TITLE] = $options[$id];
- $new_row[OPT_VOTES] = 1;
- $db->insert(VOTE_DB, $new_row);
- poll_return_results($id);
- }
- $ip[0] = $_SERVER['REMOTE_ADDR'];
- $db->insert(IP_DB, $ip);
- setcookie("vote_id", $id, time()+31556926);
poll_return_results()
- function poll_return_results($id = NULL) {
- global $db;
- $html = file_get_contents(HTML_FILE);
- $results_html = "<div id='poll-container'><div id='poll-results'><h3>Poll Results</h3>\n<dl class='graph'>\n";
- $rows = $db->selectWhere(VOTE_DB,
- new SimpleWhereClause(OPT_ID, "!=", 0), -1,
- new OrderBy(OPT_VOTES, DESCENDING, INTEGER_COMPARISON));
- foreach ($rows as $row) {
- $total_votes = $row[OPT_VOTES]+$total_votes;
- }
- foreach ($rows as $row) {
- $percent = round(($row[OPT_VOTES]/$total_votes)*100);
- if (!$row[OPT_ID] == $id) {
- $results_html .= "<dt class='bar-title'>". $row[OPT_TITLE] ."</dt><dd class='bar-container'><div id='bar". $row[OPT_ID] ."'style='width:$percent%;'> </div><strong>$percent%</strong></dd>\n";
- }
- else {
- $results_html .= "<dt class='bar-title'>". $row[OPT_TITLE] ."</dt><dd class='bar-container'><div id='bar". $row[OPT_ID] ."' style='width:$percent%;background-color:#0066cc;'> </div><strong>$percent%</strong></dd>\n";
- }
- }
- $results_html .= "</dl><p>Total Votes: ". $total_votes ."</p></div></div>\n";
- $results_regex = '/<div id="poll-container">(.*?)<\/div>/s';
- $return_html = preg_replace($results_regex, $results_html, $html);
- print $return_html;
- }
poll_return_results()
generates the poll results, takes the HTML file, replaces the form with the results, and returns the file to the client.First, lets grab the HTML file and set
$html
to it:- $html = file_get_contents(HTML_FILE);
- $results_html = "<div id='poll-container'><div id='poll-results'><h3>Poll Results</h3>\n<dl class='graph'>\n";
- $rows = $db->selectWhere(VOTE_DB,
- new SimpleWhereClause(OPT_ID, "!=", 0), -1,
- new OrderBy(OPT_VOTES, DESCENDING, INTEGER_COMPARISON));
- foreach ($rows as $row) {
- $total_votes = $row[OPT_VOTES]+$total_votes;
- }
- foreach ($rows as $row) {
- $percent = round(($row[OPT_VOTES]/$total_votes)*100);
<dl>
) styled with CSS to create bar graphs:- $results_html .= "<dt class='bar-title'>". $row[OPT_TITLE] ."</dt><dd class='bar-container'><div id='bar". $row[OPT_ID] ."'style='width:$percent%;'> </div><strong>$percent%</strong></dd>\n";
- if (!$row[OPT_ID] == $id) {
- }
- else {
- $results_html .= "<dt class='bar-title'>". $row[OPT_TITLE] ."</dt><dd class='bar-container'><div id='bar". $row[OPT_ID] ."' style='width:$percent%;background-color:#0066cc;'> </div><strong>$percent%</strong></dd>\n";
- }
- $results_html .= "</dl><p>Total Votes: ". $total_votes ."</p></div></div>\n";
<div>
:- $results_regex = '/<div id="poll-container">(.*?)<\/div>/s';
- $return_html = preg_replace($results_regex, $results_html, $html);
- print $return_html;
poll_ajax()
- function poll_ajax() {
- global $db;
- global $options;
- $id = $_GET['vote'] || $_POST['vote'];
- $ip_result = $db->selectUnique(IP_DB, 0, $_SERVER['REMOTE_ADDR']);
- if (empty($ip_result)) {
- $ip[0] = $_SERVER['REMOTE_ADDR'];
- $db->insert(IP_DB, $ip);
- if ($id != 'none') {
- $row = $db->selectUnique(VOTE_DB, OPT_ID, $id);
- if (!empty($row)) {
- $new_votes = $row[OPT_VOTES]+1;
- $db->updateSetWhere(VOTE_DB, array(OPT_VOTES => $new_votes), new SimpleWhereClause(OPT_ID, '=', $id));
- }
- else if ($options[$id]) {
- $new_row[OPT_ID] = $id;
- $new_row[OPT_TITLE] = $options[$id];
- $new_row[OPT_VOTES] = 1;
- $db->insert(VOTE_DB, $new_row);
- }
- }
- }
- $rows = $db->selectWhere(VOTE_DB, new SimpleWhereClause(OPT_ID, "!=", 0), -1, new OrderBy(OPT_VOTES, DESCENDING, INTEGER_COMPARISON));
- print json_encode($rows);
- }
poll_ajax()
takes a request from the Javascript, adds the vote to the DB, and returns the results as JSON.There are a few lines of code that are different from
poll_submit()
. The first checks if the Javascript just wants the results, and no vote should be counted:- if ($id != 'none')
- $rows = $db->selectWhere(VOTE_DB, new SimpleWhereClause(OPT_ID, "!=", 0), -1, new OrderBy(OPT_VOTES, DESCENDING, INTEGER_COMPARISON));
- print json_encode($rows);
CSS
- .graph {
- width: 250px;
- position: relative;
- rightright: 30px;
- }
- .bar-title {
- position: relative;
- float: left;
- width: 104px;
- line-height: 20px;
- margin-right: 17px;
- font-weight: bold;
- text-align: rightright;
- }
- .bar-container {
- position: relative;
- float: left;
- width: 110px;
- height: 10px;
- margin: 0px 0px 15px;
- }
- .bar-container div {
- background-color:#cc4400;
- height: 20px;
- }
- .bar-container strong {
- position: absolute;
- rightright: -32px;
- top: 0px;
- overflow: hidden;
- }
- #poll-results p {
- text-align: center;
- }
- .graph styles the container for the bars, titles and percentages. The
width
will be different for each site. - .bar-title styles the titles for the bar graphs.
- .bar-container styles the individual bar and percentage containers
- .bar-container div styles the div that the bar is applied to. To create the bars, a percentage
width
is set with PHP or Javascript. - .bar-container strong styles the percentage.
- #poll-results p styles the total votes.
Javascript
Introduction
The Javascript will intercept the submit button, send the vote with Ajax, and animate the results.First, some global variables. You should recognize the first three from the PHP.
votedID
stores the ID of the option the client voted for.- var OPT_ID = 0;
- var OPT_TITLE = 1;
- var OPT_VOTES = 2;
- var votedID;
- $(document).ready(function(){
formProcess
when it is triggered:- $("#poll").submit(formProcess);
<div>
exists, and animate the results if it does:- if ($("#poll-results").length > 0 ) {
- animateResults();
- }
loadResults()
.- if ($.cookie('vote_id'))
- $("#poll-container").empty();
- votedID = $.cookie('vote_id');
- $.getJSON("poll.php?vote=none",loadResults);
- }
formProcess()
- function formProcess(event){
- event.preventDefault();
- var id = $("input[@name='poll']:checked").attr("value");
- id = id.replace("opt",'');
- $("#poll-container").fadeOut("slow",function(){
- $(this).empty();
- votedID = id;
- $.getJSON("poll.php?vote="+id,loadResults);
- $.cookie('vote_id', id, {expires: 365});
- });
- }
formProcess()
is called by the submit event which passes it an event object. It prevents the form from doing a normal submit, checks/sets the cookies, runs an Ajax submit instead, then calls loadResults()
to convert the results to HTML.First, we need to prevent the default action (submitting the form):
- event.preventDefault();
- var id = $("input[@name='poll']:checked").attr("value");
- id = id.replace("opt",'');
input[@name='poll']:checked
is a jQuery selector that selects a <input>
with an attribute of name='poll'
that is checked. attr("value")
gets the value of the object which in our case is optn where n is the ID of the option.Now that we have the ID, we can process it. To start, we fade out the poll form, and setup an anonymous function as a callback that is run when the fade is complete. Animations don’t pause the script, so weird things happen if you don’t do it this way.
- $("#poll-container").fadeOut("slow",function(){
empty()
:- $(this).empty();
$(this)
is jQuery shorthand for the DOM element that the fade was applied to.jQuery has some other shortcut functions, including
$.getJSON()
which does GET request for a JSON object. When we have the object, we call loadResults()
with it:- $.getJSON("poll.php?vote="+id,loadResults);
- $.cookie('vote_id', id, {expires: 365});
loadResults()
- function loadResults(data) {
- var total_votes = 0;
- var percent;
- for (id in data) {
- total_votes = total_votes+parseInt(data[id][OPT_VOTES]);
- }
- var results_html = "<div id='poll-results'><h3>Poll Results</h3>\n<dl class='graph'>\n";
- for (id in data) {
- percent = Math.round((parseInt(data[id][OPT_VOTES])/parseInt(total_votes))*100);
- if (data[id][OPT_ID] !== votedID) {
- results_html = results_html+"<dt class='bar-title'>"+data[id][OPT_TITLE]+"</dt><dd class='bar-container'><div id='bar"+data[id][OPT_ID]+"'style='width:0%;'> </div><strong>"+percent+"%</strong></dd>\n";
- } else {
- results_html = results_html+"<dt class='bar-title'>"+data[id][OPT_TITLE]+"</dt><dd class='bar-container'><div id='bar"+data[id][OPT_ID]+"'style='width:0%;background-color:#0066cc;'> </div><strong>"+percent+"%</strong></dd>\n";
- }
- }
- results_html = results_html+"</dl><p>Total Votes: "+total_votes+"</p></div>\n";
- $("#poll-container").append(results_html).fadeIn("slow",function(){
- animateResults();});
- }
loadResults()
is called by $.getJSON()
and is passed a JSON object containing the results DB. It is pretty much the same as it’s PHP counterpart poll_return_results()
with a few exceptions. The first difference is that we set the width
on all the bars to 0% because we will be animating them. The other difference is that we are using a jQuery append()
instead of regex to show the results. After the results fade in, the function calls animateResults()
. animateResults()
- function animateResults(){
- $("#poll-results div").each(function(){
- var percentage = $(this).next().text();
- $(this).css({width: "0%"}).animate({
- width: percentage}, 'slow');
- });
- }
animateResults()
iterates through each of the bars and animates the width
property based on the percentage.each()
is a jQuery function that iterates through each element that is selected:- $("#poll-results div").each(function(){
<strong>
containing the percentage.- var percentage = $(this).next().text();
width
is set to 0%, and animate it:- $(this).css({width: "0%"}).animate({
- width: percentage}, 'slow');
Enjoyed this Post?
Subscribe to our RSS Feed, Follow us on Twitter or simply recommend us to friends and colleagues!
ليست هناك تعليقات:
إرسال تعليق