Creating Your Own Ajax Poll System

Image Tutorials

Creating own ajax poll system. Today I prepared new interesting tutorial – we will creating own Poll system (AJAX) for your projects with PHP. Polls, answers and results I going to keep in single SQL table. When we will vote for one of variants – jQuery will POST data, and then we will animate our results in realtime.

Live Demo

[sociallocker]

download in package

[/sociallocker]


Now – download the source files and lets start coding !


Step 1. SQL

We will need to add one table into our database:

01 CREATE TABLE `s183_polls` (
02   `id` int(10) unsigned NOT NULL auto_increment,
03   `title` varchar(255) default '',
04   `answers` text NOT NULL,
05   `results` varchar(60) NOT NULL default '',
06   `total_votes` int(10) NOT NULL default '0',
07   `when` int(10) NOT NULL,
08   PRIMARY KEY  (`id`)
09 ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
10 INSERT INTO `s183_polls` (`id`, `title`, `answers`, `results`, `total_votes`, `when`) VALUES
11 (NULL, 'First poll question''Answer 1<sep>Answer 2<sep>Answer 3<sep>Answer 4''', 0, UNIX_TIMESTAMP()),
12 (NULL, 'Second poll question''Answer 21<sep>Answer 22<sep>Answer 23<sep>Answer 24''', 0, UNIX_TIMESTAMP()+1),
13 (NULL, 'Third poll question''Answer 31<sep>Answer 32<sep>Answer 33<sep>Answer 34''', 0, UNIX_TIMESTAMP()+2),
14 (NULL, 'Forth poll question''Answer 41<sep>Answer 42<sep>Answer 43<sep>Answer 44''', 0, UNIX_TIMESTAMP()+3),
15 (NULL, 'Fifth poll question''Answer 51<sep>Answer 52<sep>Answer 53<sep>Answer 54''', 0, UNIX_TIMESTAMP()+4);

This is pur main Polls table.

Step 2. PHP

Here are source code of our main file:

index.php

001 <?php
002 // disable  warnings
003 if (version_compare(phpversion(), "5.3.0"">=")  == 1)
004   error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
005 else
006   error_reporting(E_ALL & ~E_NOTICE);
007 require_once('classes/CMySQL.php'); // including service class to work with database
008 if ($_POST['do'] == 'vote') { // in case if we submitted poll
009     $iPollId = (int)$_POST['id'];
010     $iAnswer = (int)$_POST['answer'];
011     if ($iPollId && $iAnswer >= 0 && ! isset($_COOKIE['av' $iPollId])) {
012         // get poll info
013         $aPollInfo $GLOBALS['MySQL']->getRow("SELECT * FROM `s183_polls` WHERE `id` = '{$iPollId}'");
014         // updating of poll results
015         $aAnswers explode('<sep>'$aPollInfo['answers']);
016         $iCnt count($aAnswers);
017         $aVotes = ($aPollInfo['results'] == '') ? array_fill(0, $iCnt, 0) : explode('<sep>'$aPollInfo['results']);
018         $aVotes[$iAnswer]++;
019         $iVotesCount array_sum($aVotes);
020         $sVotes = implode('<sep>'$aVotes);
021         $GLOBALS['MySQL']->res("UPDATE `s183_polls` SET `results` = '{$sVotes}', `total_votes` = {$iVotesCount} WHERE `id` = {$iPollId}");
022         // recalculation of percents
023         $iVotesCnt $aPollInfo['total_votes'] + 1;
024         $aPercents array();
025         foreach ($aAnswers as $i => $sAnswer) {
026             $aPercents[$i] = round( (0 != $iVotesCnt ? (( $aVotes[$i] / $iVotesCnt ) * 100) : 0), 1);
027         }
028         setcookie('av' $iPollId'1', time() + 24*3600, '/'); // easy protection from duplicate votes
029         // return back to JS
030         echo json_encode($aPercents);
031         exit;
032     else {
033         exit;
034     }
035 }
036 $sCode '';
037 $iItemId = (int)$_GET['id'];
038 if ($iItemId) { // View item output
039     $aItemInfo $GLOBALS['MySQL']->getRow("SELECT * FROM `s183_polls` WHERE `id` = '{$iItemId}'"); // get poll info
040     $aAnswers explode('<sep>'$aItemInfo['answers']);
041     $iCnt count($aAnswers);
042     $aVotes = ($aItemInfo['results'] == '') ? array_fill(0, $iCnt, 0) : explode('<sep>'$aItemInfo['results']);
043     $iVotesCnt $aItemInfo['total_votes'];
044     $sAnswers '';
045     foreach ($aAnswers as $i => $sAnswer) {
046         $fPercent round((0 != $iVotesCnt ? (($aVotes[$i] / $iVotesCnt) * 100) : 0), 1);
047         $sAnswers .= "<div id='{$i}'><div>{$sAnswer} (<span>{$aVotes[$i]}</span>)</div><div class='row' style='width:{$fPercent}%'>{$fPercent}%</div></div>";
048     }
049     ob_start();
050     ?>
051 <h1><?= $aItemInfo['title'] ?></h1>
052 <h3><?= date('F j, Y'$aItemInfo['when']) ?></h3><hr />
053 <div class="answers"><?= $sAnswers ?></div>
054 <hr /><h3><a href="<?= $_SERVER['PHP_SELF'] ?>">back</a></h3>
055 <script>
056 $(function(){
057     $('.answers > div').click(function () {
058         var answer = $(this).attr('id');
059         var $span = $(this).find('span');
060         $.post('<?= $_SERVER['PHP_SELF'] ?>', {id: <?= $iItemId ?>, answer: answer, do'vote'},
061             function(data){
062                 if (data) {
063                     var da = eval('(' + data + ')');
064                     for (var p in da) {
065                         $($('.answers > div .row')[p]).animate({
066                             width: da[p] + "%"
067                         }, 500);
068                         $($('.answers > div .row')[p]).text(da[p] + "%");
069                     }
070                     $span.text(parseInt($span.text()) + 1);
071                 }
072             }
073         );
074     });
075 });
076 </script>
077     <?
078     $sCode .= ob_get_clean();
079 else {
080     $sCode .= '<h1>List of polls:</h1>';
081     // taking info about all polls from database
082     $aItems $GLOBALS['MySQL']->getAll("SELECT * FROM `s183_polls` ORDER by `when` ASC");
083     foreach ($aItems as $i => $aItemInfo) {
084         $sCode .= '<h2><a href="'.$_SERVER['PHP_SELF'].'?id='.$aItemInfo['id'].'">'.$aItemInfo['title'].'</a></h2>';
085     }
086 }
087 ?>
088 <!DOCTYPE html>
089 <html lang="en" >
090     <head>
091         <meta charset="utf-8" />
092         <title>Creating own ajax poll system | Script Tutorials</title>
093         <link href="css/main.css" rel="stylesheet" type="text/css" />
094         <script type="text/javascript" src="js/jquery-1.5.2.min.js"></script>
095     </head>
096     <body>
097         <div class="container">
098             <?= $sCode ?>
099         </div>
100         <footer>
101             <h2>Creating own own ajax poll system</h2>
102             <a href="https://www.script-tutorials.com/creating-own-ajax-poll-system/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
103         </footer>
104     </body>
105 </html>

When we open this page in first time – it will draw list of polls. Each poll unit have own page. At this page we going to display Poll title, date of adding and all possible answers. On click – script will send (POST) data to same script. In this moment we are adding this vote, and then we will send back new percentages for all variants. And jQuery will re-animate all these bars. I added my comments in most of places for better understanding.

I have another one PHP file in my project:

classes/CMySQL.php

This is service class to work with database prepared by me. This is nice class which you can use too. Database connection details present in that class file in few variables, sure that you will able to configure this to your database. I will not publish sources of this file – this is not necessary right now. Available in package.

Step 3. JS

js/jquery-1.5.2.min.js

This is just jQuery library. Available in package.

Step 4. CSS

Now – all used CSS styles:

css/main.css

01 *{
02     margin:0;
03     padding:0;
04 }
05 body {
06     background-repeat:no-repeat;
07     background-color:#bababa;
08     background-image: -webkit-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
09     background-image: -moz-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
10     background-image: -o-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
11     background-image: radial-gradient(600px 200px, circle, #eee, #bababa 40%);
12     color:#fff;
13     font:14px/1.3 Arial,sans-serif;
14     min-height:600px;
15 }
16 footer {
17     background-color:#212121;
18     bottom:0;
19     box-shadow: 0 -1px 2px #111111;
20     display:block;
21     height:70px;
22     left:0;
23     position:fixed;
24     width:100%;
25     z-index:100;
26 }
27 footer h2{
28     font-size:22px;
29     font-weight:normal;
30     left:50%;
31     margin-left:-400px;
32     padding:22px 0;
33     position:absolute;
34     width:540px;
35 }
36 footer a.stuts,a.stuts:visited{
37     border:none;
38     text-decoration:none;
39     color:#fcfcfc;
40     font-size:14px;
41     left:50%;
42     line-height:31px;
43     margin:23px 0 0 110px;
44     position:absolute;
45     top:0;
46 }
47 footer .stuts span {
48     font-size:22px;
49     font-weight:bold;
50     margin-left:5px;
51 }
52 .container {
53     border:3px #111 solid;
54     color:#000;
55     margin:20px auto;
56     padding:15px;
57     position:relative;
58     text-align:center;
59     width:500px;
60     border-radius:15px;
61     -moz-border-radius:15px;
62     -webkit-border-radius:15px;
63 }
64 .answers > div {
65     cursor:pointer;
66     margin:0 0 0 40px;
67     padding:10px;
68     text-align:left;
69 }
70 .answers > div:hover {
71     background-color: rgba(255, 255, 255, 0.4);
72 }
73 .answers div .row {
74      background-color:#0f0;
75 }

Live Demo

Conclusion

Today we built the great AJAX Poll system for your website. Sure that this material will be useful for your own projects. Good luck in your work!

Rate article