Ajax Poll Script With PHP, MySQL & jQuery

In this tutorial, we'll be creating an Ajax Poll Script that displays the results with colored and animated lines using PHP, MySQL and jQuery.

The script has a pretty easy logic and can be implemented into any website quickly by simply calling a php function like getPoll(2) which brings the second poll.

Ajax Poll Script

Download

The code has 3 parts: HTML, JavaScript (jQuery) and PHP. Let's start with the easiest one:

HTML

The HTML for the poll is generated within the PHP function which is usually nice as it is only a 1-line-code and doesn't create a visual pollution in the overall HTML.

[sourcecode language=”html”]

Poll Question 1

  • Answer1 for Poll1
  •  
  • Answer2 for Poll1
  •  

Ajax Loader

[/sourcecode]

 

There is nothing original here. In one of the list items, we mention the answer and provide a unique ID for it which matches that answer's answerID in the database. For the other list item, we reserve it for the colored line, again by giving it the unique ID.

PHP

We first include our db connection file and handle the posted items from the Ajax requests

[sourcecode language=”php”]
require(“db.php”);
//GETTING VARIABLES START
if (isset($_POST[‘action’])) {
$action = mysql_real_escape_string($_POST[‘action’]);
}
if (isset($_POST[‘pollAnswerID’])) {
$pollAnswerID = mysql_real_escape_string($_POST[‘pollAnswerID’]);
}
//GETTING VARIABLES END
[/sourcecode]

After that, create the function getPoll which simply loops through the database and creates the HTML for the poll mentioned above.

[sourcecode language=”php”]
function getPoll($pollID){
$query = “SELECT * FROM polls LEFT JOIN pollAnswers ON polls.pollID = pollAnswers.pollID WHERE polls.pollID = ” . $pollID . ” ORDER By pollAnswerListing ASC”;
$result = mysql_query($query);
//echo $query;jquery

$pollStartHtml = ”;
$pollAnswersHtml = ”;

while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$pollQuestion = $row[‘pollQuestion’];
$pollAnswerID = $row[‘pollAnswerID’];
$pollAnswerValue = $row[‘pollAnswerValue’];

if ($pollStartHtml == ”) {
$pollStartHtml = ‘

‘ . $pollQuestion .’

    ‘;
    $pollEndHtml = ‘

Ajax Loader

‘;
}
$pollAnswersHtml = $pollAnswersHtml . ‘

  • ‘ . $pollAnswerValue .’
  • ‘;
    $pollAnswersHtml = $pollAnswersHtml . ‘

  • ‘;
    }
    echo $pollStartHtml . $pollAnswersHtml . $pollEndHtml;
    }
    [/sourcecode]

     

    This getPollID function below is for easily getting the ID of the related polls by providing an answerID:

    [sourcecode language=”php”]
    function getPollID($pollAnswerID){
    $query = “SELECT pollID FROM pollAnswers WHERE pollAnswerID = “.$pollAnswerID.” LIMIT 1″;
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);

    return $row[‘pollID’];
    }
    [/sourcecode]

    And, the getPollResults function which is kinda tricky but not that much.

    When ran, it returns a string like: 1|13|#ffcc00-2|32|#00ff00-3|18|#cc0000-63" which the first number is the answerID, second is the points it has and third is the color for that answer's animated line.

    The last number is the sum of all points for easily calculating percentages.

    The string is parsed in the JavaScript side later on.

    [sourcecode language=”php”]
    function getPollResults($pollID){
    $colorArray = array(1 => “#ffcc00”, “#00ff00”, “#cc0000”, “#0066cc”, “#ff0099”, “#ffcc00”, “#00ff00”, “#cc0000”, “#0066cc”, “#ff0099”);
    $colorCounter = 1;
    $query = “SELECT pollAnswerID, pollAnswerPoints FROM pollAnswers WHERE pollID = “.$pollID.””;
    $result = mysql_query($query);
    while($row = mysql_fetch_array($result))
    {
    if ($pollResults == “”) {
    $pollResults = $row[‘pollAnswerID’] . “|” . $row[‘pollAnswerPoints’] . “|” . $colorArray[$colorCounter];
    } else {
    $pollResults = $pollResults . “-” . $row[‘pollAnswerID’] . “|” . $row[‘pollAnswerPoints’] . “|” . $colorArray[$colorCounter];
    }
    $colorCounter = $colorCounter + 1;
    }
    $query = “SELECT SUM(pollAnswerPoints) FROM pollAnswers WHERE pollID = “.$pollID.””;
    $result = mysql_query($query);
    $row = mysql_fetch_array( $result );
    $pollResults = $pollResults . “-” . $row[‘SUM(pollAnswerPoints)’];
    echo $pollResults;
    }
    [/sourcecode]

    The last PHP code is the voting part which also sets a cookie:

    [sourcecode language=”php”]
    //VOTE START
    if ($action == “vote”){

    if (isset($_COOKIE[“poll” . getPollID($pollAnswerID)])) {
    echo “voted”;
    } else {
    $query = “UPDATE pollAnswers SET pollAnswerPoints = pollAnswerPoints + 1 WHERE pollAnswerID = “.$pollAnswerID.””;
    mysql_query($query) or die(‘Error, insert query failed’);
    setcookie(“poll” . getPollID($pollAnswerID), 1, time()+259200, “/”, “.webresourcesdepot.com”);
    getPollResults(1);
    }
    }
    //VOTE END

    if (mysql_real_escape_string($_GET[‘cleanCookie’]) == 1){
    setcookie(“poll1”, “”, time()-3600, “/”, “.webresourcesdepot.com”);
    header(‘Location: http://webresources.wpengine.com/wp-content/uploads/file/ajax-poll-script/’);
    }
    [/sourcecode]

    jQuery (JavaScript)

    It is only an Ajax request that posts the selected answer to the PHP code, gets the string in return, parses it and makes some show/hide tricks for displaying and hiding the messages or loaders.

    Here it is:

    [sourcecode language=”javascript”]
    $(document).ready(function() {

    $(“#pollAjaxLoader”).hide(); //hide the ajax loader
    $(“#pollMessage”).hide(); //hide the ajax loader
    $(“#pollSubmit”).click(function() {
    var pollAnswerVal = $(‘input:radio[name=pollAnswerID]:checked’).val();//Getting the value of a selected radio element.
    if ($(‘input:radio[name=pollAnswerID]:checked’).length) {
    $(“#pollAjaxLoader”).show(); //show the ajax loader
    $.ajax({
    type: “POST”,
    url: “inc/functions.php”,
    data: { pollAnswerID: pollAnswerVal, action: “vote” },
    success: function(theResponse) {
    //the functions.php returns a response like “1|13|#ffcc00-2|32|#00ff00-3|18|#cc0000-63” which the first number is the answerID, second is the points it has and third is the color for that answer’s graph. The last number is the sum of all points for easilt calculating percentages.
    if (theResponse == “voted”) {
    $(“#pollAjaxLoader”).hide(); //hide the ajax loader
    $(“#pollMessage”).html(“sorry, you already voted.”).fadeTo(“slow”, 1);
    } else {
    var numberOfAnswers = (theResponse).split(“-“).length-2;//calculate the number of answers
    var splittedResponse = (theResponse).split(“-“);
    var pollAnswerTotalPoints = splittedResponse[numberOfAnswers+1];

    for (i=0;i<=numberOfAnswers;i++) { var splittedAnswer = (splittedResponse[i]).split("|"); var pollAnswerID = (splittedAnswer[0]); var pollAnswerPoints = (splittedAnswer[1]); var pollAnswerColor = (splittedAnswer[2]); var pollPercentage = (100 * pollAnswerPoints / pollAnswerTotalPoints); $(".pollChart" + pollAnswerID).css("background-color",pollAnswerColor); $(".pollChart" + pollAnswerID).animate({width:pollPercentage + "%"}); $("#pollAnswer" + pollAnswerID).html(" (" + Math.round(pollPercentage) + "% - " + pollAnswerPoints + " votes)"); $("#pollRadioButton" + pollAnswerID).attr("disabled", "disabled"); //disable the radio buttons } $("#pollAjaxLoader").hide(); //hide the ajax loader again $("#pollSubmit").attr("disabled", "disabled"); //disable the submit button } } }); return false; } else { $("#pollMessage").html("please select an answer.").fadeTo("slow", 1, function(){ setTimeout(function() { $("#pollMessage").fadeOut("slow"); }, 3000); }); return false; } }); }); [/sourcecode]

    The JavaScript code is well-commented and is pretty self-explanatory. Don't let the number of lines afraid you, most of them are just the make-up.

    That's all.

    Search