How to quickly make a poll using PHP and jQuery, part one

Creating a fast and easy voting system

Do you need to have a poll on your website but do not want to use more heavy and restrictive plugins? Here you go!

It is actually pretty easy to create a polling system by yourself for your website. In the first part of this post, you will learn how to do it and in the upcoming second part, you will learn how to push it to the next level to fulfill your specific needs. It is now time to open your favorite text editor and to start working!

If you only want to get the project’s files, it’s here.

To watch and test the poll live, here is the demo.


Database and Files Organization

Technically, you could organize the project’s files as you wish. However, you might need to adjust parts of the code. In this example, the poll is not linked to any website, so we will do things simply.

Let’s start with the database. You can use an old or new database, just create a new table named pollitems with 3 columns (name, image ans votes). You should end up with something like this:

Database organization

You can now start adding in the DB each element that you want in your poll. The column name will be the element’s name as shown on the website. The image’s column will be the filename of the linked image of each element and for the last one, votes, just type a zero (0).

Next, on your server, at the root of your project folder, you will create five new files: f.php, index.php, poll.js, styles.css and voteProcess.php. You will also need to add a folder to contain the project’s images, I will simply call it images. You can now add each element’s image to the folder.

files organization

Then link the index.php to styles.css and to poll.js. Also include the file f.php. You will need to add jQuery too, here I call it through a CDN.

<head>
    <meta charset="UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="poll.js"></script>
    <link rel="stylesheet" href="styles.css">
    <title>PHP Poll</title>
</head>

But what are all these files for?

f.php: This file will regroup all of our PHP functions.
Index.php: The homepage of the project, this file will show the poll.
poll.js: This file will regroup every JavaScript and jQuery needs.
styles.css: Typical stylesheet file, you can customize this as much as you want. Therefore, I will not get into too much details on this file in the post.
voteProcess.php: This is the file that will be called VIA AJAX to submit votes.

Creating our PHP Functions

Open f.php, we will now create the functions needed for the project. Please take note that I am using PDO to access the database. You can do it otherwise but you might need to adjust some of the code. So, first step, we need to connect to the database.

function Query($z){
	$user = "USERNAME";
	$pass = "PASSWORD";
	$dbname="DATABASE NAME";
	$dbh = new PDO('mysql:host=localhost;dbname='.$dbname, $user, $pass);
	$dbh->query('SET NAMES utf8');
	return $dbh->query($z);
}

We will then create the 4 functions we will use. Nothing too intricate here.

function Query($z){
	$user = "USERNAME";
	$pass = "PASSWORD";
	$dbname="DATABASE NAME";
	$dbh = new PDO('mysql:host=localhost;dbname='.$dbname, $user, $pass);
	$dbh->query('SET NAMES utf8');
	return $dbh->query($z);
}

function selectAllItemsRand(){
    $contents = Query("SELECT * FROM pollitems ORDER BY RAND()");
	return $contents;
}

function selectAllItemsByVote(){
    $contents = Query("SELECT * FROM pollitems ORDER BY `votes` DESC");
	return $contents;
}

function selectVoteFrom($name){
    $contents = Query("SELECT * FROM pollitems WHERE `name`='".$name."'");
	foreach($contents as $content){
		return $content['votes'];
	}
}

function addVoteTo($name){
    Query("UPDATE `pollitems` SET `votes`='".(selectVoteFrom($name)+1)."' WHERE `name`='".$name."'");
}

But what are all these functions for?

selectAllItemsRand: This function selects all the elements in a random order. Why random? Because this way, no element will be favoured by its position on the page.
selectAllItemsByVote: This function selects all elements ordered by the number of votes. This will be used to show the poll’s results in the right order.
selectVoteFrom: This function allows us to get the number of votes for a specific element. It will be useful in the next function.
addVoteTo: This function adds a vote to an element. We get the number of votes and add one more to it then we update the amount in the database.

The Poll’s Markup

Now that our functions are created, let’s open index.php again. The HTML markup I will make here is very basic, you can use it as is or as a guideline. The most important part here is the PHP loop that will get all the items to show.

<body>
    <div class="wrapper poll">
        <h1>Vote for your favorite punk rock band</h1>
        <div class="pollitems">
            <?php
                $pollitems = selectAllItemsRand();
                $i = 0;
                foreach($pollitems as $pollitem){
            ?>
            <input type="radio" class="pollInput" name="pollInput" value="<?=$pollitem['name'];?>" id="poll<?=$i;?>">
            <label for="poll<?=$i;?>" class="pollLabel">
                <img src="images/<?=$pollitem['image'];?>" alt="<?=$pollitem['name'];?>">
                <h2><?=$pollitem['name'];?></h2>
            </label>
            <?php
                    $i++;
                }
            ?>
        </div>
        <a href="#" class="submitPoll">Vote</a>
    </div>
</body>

At this point, if you open the project in your browser, you should see the poll’s items. Make sure it’s the case before going forward.

The next step is to give a good look to the poll with CSS. You can copy the styles I used in styles.css or make your own. That’s up to you. If you have not already, you can download the project’s files here.

Planning the File that will be Loaded in AJAX

We will now make the file that will send the votes to the database and that will return the results to us. Open voteProcess.php and copy/paste this piece of code.

<?php
include('f.php');
$voteValue = $_POST['value'];
addVoteTo($voteValue);
?>
<h2 class="resultH2">You voted for : <strong><?=$voteValue;?></strong></h2>
<table class="results">
<?php
$pollItems = selectAllItemsByVote();
foreach($pollItems as $pollItem){
?>
<tr>
    <td><strong><?=$pollItem['name'];?> :</strong></td>
    <td><?=$pollItem['votes'];?></td>
</tr>
<?php
}
?>
</table>

This code gets the voted item’s name and sends it to the function addVoteTo. The last part of the code is a PHP loop that looks like the one on the index.php. The loop will return a table of the results to show it to the user after their vote.

Managing Errors and Submitting the Poll Using jQuery

We are almost done. Open poll.js, we will add a bit of code to it to link our poll to our submission file and to handle errors.

First, we want to create an error message if the user submits the poll without any selection. Here, we use the class “enabled” to check if an item has been selected or not. Once this validation is done, we will send the data to the file voteProcess.php previously created. Then we will show the returned results to the user.

$(document).ready(function(){
    
    $(".pollLabel").click(function(){
        $("p.error").remove();
        $("a.submitPoll").addClass("enabled");
    });
    
    $("a.submitPoll").click(function(){
        if($(this).hasClass("enabled")){
            var voteValue = $("input[name='pollInput']:checked").val();
        
            $.post( "voteProcess.php", {value: voteValue}, function(data) {
                $(".wrapper.poll").slideUp(400, function() {
                    $(".wrapper.poll").html(data);
                    $(".wrapper.poll").slideDown();
                });
                
            });
            
        }else{
            $(this).before("<p class='error'>You need to select an item in order to vote.</p>");
        }
        
    });
});

 

The poll should now be fully functional. The only thing left to do is to adjust the style to your website if need be.

Try out the demo

And that is what ends the first part of this post. In the second part, we will go deeper on creating upgrades for the poll. Amongst others, we will discuss how to add a closing date to the poll and how to prevent the user from voting multiple times.

That’s all! I hope you enjoyed this post. You can contact me at any time if you need some help with the project or if you have any comments.

Any questions? Contact Jim

You like this post?

Share it!

Subscribe

Enter your email to get notified of Jim's exclusive offers. The monthly newsletter contains new projects and resources.