Last active
December 19, 2015 23:19
-
-
Save sivagao/6034232 to your computer and use it in GitHub Desktop.
Creating a dynamic poll with jQuery and PHP..
http://net.tutsplus.com/tutorials/javascript-ajax/creating-a-dynamic-poll-with-jquery-and-php/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Simple but powerful flatfile database | |
* See http://lukeplant.me.uk/resources/flatfile/ for documentation and examples | |
*/ | |
?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" | |
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> | |
<html xmlns="http://www.w3.org/1999/xhtml"> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> | |
<title>jQuery Poll Demo</title> | |
<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> | |
</head> | |
<body> | |
<div id="container"> | |
<div id="header"> | |
<h1>jQuery Poll Demo</h1> | |
<h2>Because reloading the page is not in <em>style</em></h2><br /><hr /> | |
</div> | |
<div id="left"> | |
<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> | |
</div> | |
<div id="main"> | |
<h3>Lorem Ipsum</h3> | |
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla fringilla, leo id placerat facilisis, turpis nisl aliquam ante, nec accumsan ipsum felis dictum velit. Nullam ut lorem. Nam molestie. Vivamus ullamcorper consequat nulla. Donec malesuada. Ut dapibus cursus ligula. Maecenas eu turpis. Integer ultrices hendrerit eros. Ut cursus. Cras at lectus ut est pharetra viverra. In mattis. Aliquam tortor nulla, iaculis in, vestibulum interdum, aliquet non, nunc. Donec erat. Nulla placerat commodo metus. Vestibulum suscipit, dui eu tristique tempor, lorem lorem porttitor lectus, in tincidunt urna neque sed mi.</p> | |
<p>Nulla et risus. Morbi in ante non lectus eleifend rutrum. Nam mi elit, blandit eu, vestibulum eu, facilisis facilisis, dolor. Integer dignissim, erat eu fringilla vehicula, lacus magna aliquam ante, at suscipit tortor dui in ipsum. Nulla facilisis rutrum nisi. Cras fringilla commodo arcu. Donec vestibulum sollicitudin dolor. Fusce lectus mauris, lobortis sit amet, malesuada vitae, aliquet vitae, ipsum. Quisque posuere. Curabitur ante quam, sodales quis, feugiat in, pharetra eget, est. Aliquam quis enim. Vivamus in dolor. Phasellus ut lacus id nulla fringilla tincidunt. Praesent turpis. Phasellus tellus nisi, tempor in, varius at, cursus eget, risus. Duis luctus dictum tortor. Donec consequat massa. Duis dictum.</p> | |
</div> | |
<div id="footer"> | |
<hr /> | |
<p class="left"><a href="http://jigsaw.w3.org/css-validator/">CSS</a> | <a href="http://validator.w3.org/check?uri=referer">XHTML 1.0</a></p> | |
<p class="right">Code by Jonathan Rudenberg | <a href="http://www.oswd.org/design/information/id/3621">Design</a> by <a href="http://syndicateme.net/">syndicateme.net</a> @ <a href="http://www.oswd.org/">OSWD</a></p> | |
</div> | |
</div> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Global variable definitions | |
// DB column numbers | |
var OPT_ID = 0; | |
var OPT_TITLE = 1; | |
var OPT_VOTES = 2; | |
var votedID; | |
$(document).ready(function(){ | |
$("#poll").submit(formProcess); // setup the submit handler | |
if ($("#poll-results").length > 0 ) { | |
animateResults(); | |
} | |
if ($.cookie('vote_id')) { | |
$("#poll-container").empty(); | |
votedID = $.cookie('vote_id'); | |
$.getJSON("poll.php?vote=none",loadResults); | |
} | |
}); | |
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}); | |
}); | |
} | |
function animateResults(){ | |
$("#poll-results div").each(function(){ | |
var percentage = $(this).next().text(); | |
$(this).css({width: "0%"}).animate({ | |
width: percentage}, 'slow'); | |
}); | |
} | |
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();}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Poll option definitions | |
$options[1] = 'jQuery'; | |
$options[2] = 'Ext JS'; | |
$options[3] = 'Dojo'; | |
$options[4] = 'Prototype'; | |
$options[5] = 'YUI'; | |
$options[6] = 'mootools'; | |
// Column definitions | |
define('OPT_ID', 0); | |
define('OPT_TITLE', 1); | |
define('OPT_VOTES', 2); | |
define('HTML_FILE', 'poll.html'); | |
// Initialize the DB | |
require_once('flatfile.php'); | |
$db = new Flatfile(); | |
$db->datadir = 'data/'; | |
define('VOTE_DB', 'votes.txt'); | |
define('IP_DB', 'ips.txt'); | |
if ($_GET['poll'] || $_POST['poll']) { | |
poll_submit(); | |
} | |
else if ($_GET['vote'] || $_POST['vote']) { | |
poll_ajax(); | |
} | |
else { | |
poll_default(); | |
} | |
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); | |
} | |
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); // cookie expires in one year | |
$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); // cookie expires in one year | |
$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); | |
} | |
} | |
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']); | |
} | |
} | |
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; | |
} | |
if (!function_exists('json_encode')) { // json_encode was added in 5.2.0, this is a replacement function if the PHP version is old | |
function json_encode($a=false) { | |
if (is_null($a)) return 'null'; | |
if ($a === false) return 'false'; | |
if ($a === true) return 'true'; | |
if (is_scalar($a)) { | |
if (is_float($a)) { | |
// Always use "." for floats. | |
return floatval(str_replace(",", ".", strval($a))); | |
} | |
if (is_string($a)) { | |
static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"')); | |
return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"'; | |
} | |
else | |
return $a; | |
} | |
$isList = true; | |
for ($i = 0, reset($a); $i < count($a); $i++, next($a)) { | |
if (key($a) !== $i) { | |
$isList = false; | |
break; | |
} | |
} | |
$result = array(); | |
if ($isList) { | |
foreach ($a as $v) $result[] = json_encode($v); | |
return '[' . join(',', $result) . ']'; | |
} | |
else { | |
foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v); | |
return '{' . join(',', $result) . '}'; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
body { | |
font-family: arial, verdana, helvetica, sans-serif; | |
font-size: 12px; | |
cursor: default; | |
background-color: #FFFFFF | |
} | |
* { | |
margin: 0px; | |
padding: 0px; | |
text-decoration: none; | |
} | |
html { | |
height: 100%; | |
margin-bottom: 1px; | |
} | |
#container { | |
width: 80%; | |
margin-right: auto; | |
margin-left: auto; | |
text-align: left; | |
background-color: #FFFFFF; | |
} | |
#header { | |
width: 100%; | |
padding-top: 15px; | |
} | |
.spacer { | |
width: 100%; | |
height: 15px; | |
} | |
hr { | |
border: 0px; | |
color: #CCCCCC; | |
background-color: #CDCDCD; | |
height: 1px; | |
width: 100%; | |
text-align: left; | |
} | |
h1 { | |
font-size: 28px; | |
color: #cc0000; | |
background-color: #FFFFFF; | |
font-family: Arial, Verdana, Helvetica, sans-serif; | |
font-weight: 300; | |
} | |
h2 { | |
font-size: 15px; | |
color: gray; | |
font-family: Arial, Verdana, Helvetica, sans-serif; | |
font-weight: 300; | |
background-color: #FFFFFF; | |
} | |
h3 { | |
color: #cc0000; | |
font-size: 15px; | |
text-align: left; | |
font-weight: 300; | |
padding: 5px; | |
margin-top: 5px; | |
} | |
#left { | |
float: left; | |
width: 250px; | |
background-color: #FFFFFF; | |
color: black; | |
} | |
#main { | |
margin: 5px 5px 5px 260px; | |
padding: 15px; | |
border-left: 1px solid silver; | |
} | |
p { | |
color: black; | |
background-color: #FFFFFF; | |
line-height: 20px; | |
padding: 5px; | |
} | |
a { | |
color: #cc0000; | |
background-color: #FFFFFF; | |
text-decoration: none; | |
} | |
a:hover { | |
color: #cc0000; | |
background-color: #FFFFFF; | |
text-decoration: underline; | |
} | |
#footer { | |
clear: both; | |
font-size: 12px; | |
font-family: Verdana, Arial, Helvetica, sans-serif; | |
} | |
.right { | |
color: gray; | |
background-color: #FFFFFF; | |
float: right; | |
font-size: 100%; | |
margin-top: 5px; | |
} | |
.left { | |
color: gray; | |
background-color: #FFFFFF; | |
float: left; | |
font-size: 100%; | |
margin-top: 5px; | |
} | |
/* Bar Graphs */ | |
.graph { | |
width: 250px; | |
position: relative; | |
right: 30px; | |
} | |
.bar-title { | |
position: relative; | |
float: left; | |
width: 104px; | |
line-height: 20px; | |
margin-right: 17px; | |
font-weight: bold; | |
text-align: right; | |
} | |
.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; | |
right: -32px; | |
top: 0px; | |
overflow: hidden; | |
} | |
#poll-results p { | |
text-align: center; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment