الاثنين، فبراير 14، 2011

درس برمجة سكريبت تصويت بالأجاكس Creating a Dynamic Poll with jQuery and PHP

Creating a Dynamic Poll with jQuery and PHP

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.

  1. HTML
  2. PHP
    1. Introduction
    2. poll_default()
    3. poll_submit()
    4. poll_return_results()
    5. poll_ajax()
  3. CSS
  4. Javascript
    1. Introduction
    2. formProcess()
    3. loadResults()
    4. animateResults()

HTML

Let’s get our <head> set up:
  1. <link href="style.css" rel="stylesheet" type="text/css" />  
  2. <script src="jquery.js" type="text/javascript" charset="utf-8"></script>  
  3. <script src="jquery.cookie.js" type="text/javascript" charset="utf-8"></script>  
  4. <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.
Next, we’ll create a simple poll form:
Poll
  1. <div id="poll-container">  
  2.     <h3>Poll</h3>  
  3.     <form id='poll' action="poll.php" method="post" accept-charset="utf-8">  
  4.         <p>Pick your favorite Javascript framework:</p>  
  5.         <p><input type="radio" name="poll" value="opt1" id="opt1" /><label for='opt1'>&nbsp;jQuery</label><br />  
  6.         <input type="radio" name="poll" value="opt2" id="opt2" /><label for='opt2'>&nbsp;Ext JS</label><br />  
  7.         <input type="radio" name="poll" value="opt3" id="opt3" /><label for='opt3'>&nbsp;Dojo</label><br />  
  8.         <input type="radio" name="poll" value="opt4" id="opt4" /><label for='opt4'>&nbsp;Prototype</label><br />  
  9.         <input type="radio" name="poll" value="opt5" id="opt5" /><label for='opt5'>&nbsp;YUI</label><br />  
  10.         <input type="radio" name="poll" value="opt6" id="opt6" /><label for='opt6'>&nbsp;mootools</label><br /><br />  
  11.         <input type="submit" value="Vote &rarr;" /></p>  
  12.     </form>  
  13. </div>  
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. &nbsp; is just a HTML entity encoded space, and &rarr; is an arrow: →.

PHP

Introduction

If Javascript is disabled, the PHP will:
  1. Take GET/POST requests from the form
  2. Set/check a cookie
  3. Make sure the request is from a unique IP
  4. Store the vote in a flat file DB
  5. Return the results included with a HTML file
If Javascript is enabled, the PHP will:
  1. Take GET/POST requests from the Javascript
  2. Make sure the request is from a unique IP
  3. Store the vote in a flat file DB
  4. Return the results as JSON
For the flat file DB we will be using a package written by Luke Plant.
First, we need an array with the names and IDs of the poll options:
  1. <?php  
  2. $options[1] = 'jQuery';  
  3. $options[2] = 'Ext JS';  
  4. $options[3] = 'Dojo';  
  5. $options[4] = 'Prototype';  
  6. $options[5] = 'YUI';  
  7. $options[6] = 'mootools';  
The flatfile package uses numbers for the column identifiers, so lets set some constants to convert those to names:
  1. define('OPT_ID', 0);  
  2. define('OPT_TITLE', 1);  
  3. define('OPT_VOTES', 2);  
When the form is submitted, PHP needs to know what file to insert the results into and return, so we set another constant:
  1. define('HTML_FILE''index.html');  
We need to include flatfile.php and initialize a database object:
  1. require_once('flatfile.php');  
  2. $db = new Flatfile();  
The flat files are just text files stored in the data directory:
  1. $db->datadir = 'data/';  
  2. define('VOTE_DB''votes.txt');  
  3. define('IP_DB''ips.txt');  
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 HTML_FILE.
  1. if ($_GET['poll'] || $_POST['poll']) {  
  2.   poll_submit();  
  3. }  
  4. else if ($_GET['vote'] || $_POST['vote']) {  
  5.   poll_ajax();  
  6. }  
  7. else {  
  8.   poll_default();  
  9. }  

poll_default()

  1. function poll_default() {  
  2.   global $db;  
  3.   
  4.   $ip_result = $db->selectUnique(IP_DB, 0, $_SERVER['REMOTE_ADDR']);  
  5.   
  6.   if (!isset($_COOKIE['vote_id']) && empty($ip_result)) {  
  7.     print file_get_contents(HTML_FILE);  
  8.   }  
  9.   else {  
  10.     poll_return_results($_COOKIE['vote_id']);  
  11.   }  
  12. }  
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:
  1. $ip_result = $db->selectUnique(IP_DB, 0, $_SERVER['REMOTE_ADDR']);  
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:
  1. if (!isset($_COOKIE['vote_id']) && empty($ip_result)) {  
  2.   print file_get_contents(HTML_FILE);  
  3. }  
  4. else {  
  5.   poll_return_results($_COOKIE['vote_id']);  
  6. }  

poll_submit()

  1. function poll_submit() {  
  2.   global $db;  
  3.   global $options;  
  4.   
  5.   $id = $_GET['poll'] || $_POST['poll'];  
  6.   $id = str_replace("opt"''$id);  
  7.   
  8.   $ip_result = $db->selectUnique(IP_DB, 0, $_SERVER['REMOTE_ADDR']);  
  9.   
  10.   if (!isset($_COOKIE['vote_id']) && empty($ip_result)) {  
  11.     $row = $db->selectUnique(VOTE_DB, OPT_ID, $id);  
  12.     if (!empty($row)) {  
  13.       $ip[0] = $_SERVER['REMOTE_ADDR'];  
  14.       $db->insert(IP_DB, $ip);  
  15.   
  16.       setcookie("vote_id"$id, time()+31556926);  
  17.   
  18.       $new_votes = $row[OPT_VOTES]+1;  
  19.       $db->updateSetWhere(VOTE_DB, array(OPT_VOTES => $new_votes), new SimpleWhereClause(OPT_ID, '='$id));  
  20.   
  21.       poll_return_results($id);  
  22.     }  
  23.     else if ($options[$id]) {  
  24.       $ip[0] = $_SERVER['REMOTE_ADDR'];  
  25.       $db->insert(IP_DB, $ip);  
  26.   
  27.       setcookie("vote_id"$id, time()+31556926);  
  28.   
  29.       $new_row[OPT_ID] = $id;  
  30.       $new_row[OPT_TITLE] = $options[$id];  
  31.       $new_row[OPT_VOTES] = 1;  
  32.       $db->insert(VOTE_DB, $new_row);  
  33.   
  34.       poll_return_results($id);  
  35.     }  
  36.   }  
  37.   else {  
  38.     poll_return_results($id);  
  39.   }  
  40. }  
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:
  1. $id = $_GET['poll'] || $_POST['poll'];  
  2. $id = str_replace("opt"''$id);  
We need to check whether the option is in the DB yet:
  1. $row = $db->selectUnique(VOTE_DB, OPT_ID, $id);  
If it is in the DB (result not empty), we need to run an updateSetWhere(). If it isn’t we need to do an insert():
  1. if (!empty($row)) {  
  2.   $new_votes = $row[OPT_VOTES]+1;  
  3.   $db->updateSetWhere(VOTE_DB, array(OPT_VOTES => $new_votes), new SimpleWhereClause(OPT_ID, '='$id));  
  4.   
  5.   poll_return_results($id);  
  6. }  
  7. else if ($options[$id]) {  
  8.   $new_row[OPT_ID] = $id;  
  9.   $new_row[OPT_TITLE] = $options[$id];  
  10.   $new_row[OPT_VOTES] = 1;  
  11.   $db->insert(VOTE_DB, $new_row);  
  12.   
  13.   poll_return_results($id);  
  14. }  
Either way, we need to insert the IP into the DB, and set a cookie (expires in one year):
  1. $ip[0] = $_SERVER['REMOTE_ADDR'];  
  2. $db->insert(IP_DB, $ip);  
  3.   
  4. setcookie("vote_id"$id, time()+31556926);  

poll_return_results()

  1. function poll_return_results($id = NULL) {  
  2.     global $db;  
  3.   
  4.     $html = file_get_contents(HTML_FILE);  
  5.     $results_html = "<div id='poll-container'><div id='poll-results'><h3>Poll Results</h3>\n<dl class='graph'>\n";  
  6.   
  7.     $rows = $db->selectWhere(VOTE_DB,  
  8.       new SimpleWhereClause(OPT_ID, "!=", 0), -1,  
  9.       new OrderBy(OPT_VOTES, DESCENDING, INTEGER_COMPARISON));  
  10.   
  11.     foreach ($rows as $row) {  
  12.       $total_votes = $row[OPT_VOTES]+$total_votes;  
  13.     }  
  14.   
  15.     foreach ($rows as $row) {  
  16.       $percent = round(($row[OPT_VOTES]/$total_votes)*100);  
  17.       if (!$row[OPT_ID] == $id) {  
  18.         $results_html .= "<dt class='bar-title'>"$row[OPT_TITLE] ."</dt><dd class='bar-container'><div id='bar"$row[OPT_ID] ."'style='width:$percent%;'>&nbsp;</div><strong>$percent%</strong></dd>\n";  
  19.       }  
  20.       else {  
  21.         $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;'>&nbsp;</div><strong>$percent%</strong></dd>\n";  
  22.       }  
  23.     }  
  24.   
  25.     $results_html .= "</dl><p>Total Votes: "$total_votes ."</p></div></div>\n";  
  26.   
  27.     $results_regex = '/<div id="poll-container">(.*?)<\/div>/s';  
  28.     $return_html = preg_replace($results_regex$results_html$html);  
  29.     print $return_html;  
  30. }  
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:
  1. $html = file_get_contents(HTML_FILE);  
Next, we start the results HTML structure:
  1. $results_html = "<div id='poll-container'><div id='poll-results'><h3>Poll Results</h3>\n<dl class='graph'>\n";  
To create the results HTML we need to get all the rows (options) from the DB sorted by number of votes:
  1. $rows = $db->selectWhere(VOTE_DB,  
  2.   new SimpleWhereClause(OPT_ID, "!=", 0), -1,  
  3.   new OrderBy(OPT_VOTES, DESCENDING, INTEGER_COMPARISON));  
We also need the total votes to calculate percentages:

  1. foreach ($rows as $row) {  
  2.   $total_votes = $row[OPT_VOTES]+$total_votes;  
  3. }  
Next, we calculate the percentage of votes the current option has:
  1. foreach ($rows as $row) {  
  2.   $percent = round(($row[OPT_VOTES]/$total_votes)*100);  
The HTML for the results will be a definition list (<dl>) styled with CSS to create bar graphs:
  1. $results_html .= "<dt class='bar-title'>"$row[OPT_TITLE] ."</dt><dd class='bar-container'><div id='bar"$row[OPT_ID] ."'style='width:$percent%;'>&nbsp;</div><strong>$percent%</strong></dd>\n";  
Also, we should check if the current option is the one the client voted for, and change the color:
  1. if (!$row[OPT_ID] == $id) {  
  2.   
  3. }  
  4. else {  
  5.   $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;'>&nbsp;</div><strong>$percent%</strong></dd>\n";  
  6. }  
Here, we add a total vote count and close the html tags:
  1. $results_html .= "</dl><p>Total Votes: "$total_votes ."</p></div></div>\n";  
This is a regex that finds the poll-container <div>:
  1. $results_regex = '/<div id="poll-container">(.*?)<\/div>/s';  
The last step in this function is to replace the poll form with the results using the regex, and return the result:
  1. $return_html = preg_replace($results_regex$results_html$html);  
  2. print $return_html;  

poll_ajax()

  1. function poll_ajax() {  
  2.   global $db;  
  3.   global $options;  
  4.   
  5.   $id = $_GET['vote'] || $_POST['vote'];  
  6.   
  7.   $ip_result = $db->selectUnique(IP_DB, 0, $_SERVER['REMOTE_ADDR']);  
  8.   
  9.   if (empty($ip_result)) {  
  10.     $ip[0] = $_SERVER['REMOTE_ADDR'];  
  11.     $db->insert(IP_DB, $ip);  
  12.   
  13.     if ($id != 'none') {  
  14.       $row = $db->selectUnique(VOTE_DB, OPT_ID, $id);  
  15.       if (!empty($row)) {  
  16.         $new_votes = $row[OPT_VOTES]+1;  
  17.   
  18.         $db->updateSetWhere(VOTE_DB, array(OPT_VOTES => $new_votes), new SimpleWhereClause(OPT_ID, '='$id));  
  19.       }  
  20.       else if ($options[$id]) {  
  21.         $new_row[OPT_ID] = $id;  
  22.         $new_row[OPT_TITLE] = $options[$id];  
  23.         $new_row[OPT_VOTES] = 1;  
  24.         $db->insert(VOTE_DB, $new_row);  
  25.       }  
  26.     }  
  27.   }  
  28.   
  29.   $rows = $db->selectWhere(VOTE_DB, new SimpleWhereClause(OPT_ID, "!=", 0), -1, new OrderBy(OPT_VOTES, DESCENDING, INTEGER_COMPARISON));  
  30.   print json_encode($rows);  
  31. }  
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:
  1. if ($id != 'none')  
The other two lines select the whole DB and return it as JSON:
  1. $rows = $db->selectWhere(VOTE_DB, new SimpleWhereClause(OPT_ID, "!=", 0), -1, new OrderBy(OPT_VOTES, DESCENDING, INTEGER_COMPARISON));  
  2. print json_encode($rows);  

CSS

  1. .graph {  
  2.   width250px;  
  3.   positionrelative;  
  4.   rightright30px;  
  5. }  
  6. .bar-title {  
  7.   positionrelative;  
  8.   floatleft;  
  9.   width104px;  
  10.   line-height20px;  
  11.   margin-right17px;  
  12.   font-weightbold;  
  13.   text-alignrightright;  
  14. }  
  15. .bar-container {  
  16.   positionrelative;  
  17.   floatleft;  
  18.   width110px;  
  19.   height10px;  
  20.   margin0px 0px 15px;  
  21. }  
  22.   
  23. .bar-container div {  
  24.   background-color:#cc4400;  
  25.   height20px;  
  26. }  
  27. .bar-container strong {  
  28.   positionabsolute;  
  29.   rightright: -32px;  
  30.   top0px;  
  31.   overflowhidden;  
  32. }  
  33. #poll-results p {  
  34.   text-aligncenter;  
  35. }  
Poll Results
This CSS styles the results returned by the PHP or Javascript.
  • .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.
  1. var OPT_ID = 0;  
  2. var OPT_TITLE = 1;  
  3. var OPT_VOTES = 2;  
  4.   
  5. var votedID;  
Now we need a jQuery ready function which runs when the page loads:
  1. $(document).ready(function(){  
Inside that function we register the handler for the vote button which will run formProcess when it is triggered:
  1. $("#poll").submit(formProcess);  
We also need to check if the results <div> exists, and animate the results if it does:
  1. if ($("#poll-results").length > 0 ) {  
  2.     animateResults();  
  3. }  
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 loadResults().
  1. if ($.cookie('vote_id'))  
  2.     $("#poll-container").empty();  
  3.     votedID = $.cookie('vote_id');  
  4.     $.getJSON("poll.php?vote=none",loadResults);  
  5. }  

formProcess()

  1. function formProcess(event){  
  2.   event.preventDefault();  
  3.   
  4.   var id = $("input[@name='poll']:checked").attr("value");  
  5.   id = id.replace("opt",'');  
  6.   
  7.   $("#poll-container").fadeOut("slow",function(){  
  8.     $(this).empty();  
  9.   
  10.     votedID = id;  
  11.     $.getJSON("poll.php?vote="+id,loadResults);  
  12.   
  13.     $.cookie('vote_id', id, {expires: 365});  
  14.     });  
  15. }  
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):
  1. event.preventDefault();  
Next, we get the ID from the currently selected option:
  1. var id = $("input[@name='poll']:checked").attr("value");  
  2. 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.
  1. $("#poll-container").fadeOut("slow",function(){  
After it has faded out we can delete the form from the DOM using empty():
  1. $(this).empty();  
In this case, $(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:
  1. $.getJSON("poll.php?vote="+id,loadResults);  
The last thing to do is set the cookie:
  1. $.cookie('vote_id', id, {expires: 365});  

loadResults()

  1. function loadResults(data) {  
  2.   var total_votes = 0;  
  3.   var percent;  
  4.   
  5.   for (id in data) {  
  6.     total_votes = total_votes+parseInt(data[id][OPT_VOTES]);  
  7.   }  
  8.   
  9.   var results_html = "<div id='poll-results'><h3>Poll Results</h3>\n<dl class='graph'>\n";  
  10.   for (id in data) {  
  11.     percent = Math.round((parseInt(data[id][OPT_VOTES])/parseInt(total_votes))*100);  
  12.     if (data[id][OPT_ID] !== votedID) {  
  13.       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%;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";  
  14.     } else {  
  15.       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;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";  
  16.     }  
  17.   }  
  18.   
  19.   results_html = results_html+"</dl><p>Total Votes: "+total_votes+"</p></div>\n";  
  20.   
  21.   $("#poll-container").append(results_html).fadeIn("slow",function(){  
  22.     animateResults();});  
  23. }  
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()

  1. function animateResults(){  
  2.   $("#poll-results div").each(function(){  
  3.       var percentage = $(this).next().text();  
  4.       $(this).css({width: "0%"}).animate({  
  5.                 width: percentage}, 'slow');  
  6.   });  
  7. }  
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:
  1. $("#poll-results div").each(function(){  
First, we set the percentage to the text of the element next to the bar which is the <strong> containing the percentage.
  1. var percentage = $(this).next().text();  
Then we make sure the width is set to 0%, and animate it:
  1. $(this).css({width: "0%"}).animate({  
  2.   width: percentage}, 'slow');  
Enjoyed this Post?
Subscribe to our RSS Feed, Follow us on Twitter or simply recommend us to friends and colleagues!

ليست هناك تعليقات:

إرسال تعليق

ضع اقتراحك او اي ملاحظات او استفسارات هنا

الاسم

بريد إلكتروني *

رسالة *