Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
  1. Code
  2. Web Development

Creating a Dynamic Poll With jQuery and PHP


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()


Let’s get our <head> set up:

  • 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:


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: →.



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:

The flatfile package uses numbers for the column identifiers, so lets set some constants to convert those to names:

When the form is submitted, PHP needs to know what file to insert the results into and return, so we set another constant:

We need to include flatfile.php and initialize a database object:

The flat files are just text files stored in the data directory:

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.


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:

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:


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:

We need to check whether the option is in the DB yet:

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():

Either way, we need to insert the IP into the DB, and set a cookie (expires in one year):


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:

Next, we start the results HTML structure:

To create the results HTML we need to get all the rows (options) from the DB sorted by number of votes:

We also need the total votes to calculate percentages:

Next, we calculate the percentage of votes the current option has:

The HTML for the results will be a definition list (<dl>) styled with CSS to create bar graphs:

Also, we should check if the current option is the one the client voted for, and change the color:

Here, we add a total vote count and close the html tags:

This is a regex that finds the poll-container <div>:

The last step in this function is to replace the poll form with the results using the regex, and return the result:


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:

The other two lines select the whole DB and return it as JSON:


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.



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.

Now we need a jQuery ready function which runs when the page loads:

Inside that function we register the handler for the vote button which will run formProcess when it is triggered:

We also need to check if the results <div> exists, and animate the results if it does:

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().


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):

Next, we get the ID from the currently selected option:

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.

After it has faded out we can delete the form from the DOM using 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:

The last thing to do is set the cookie:


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() 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:

First, we set the percentage to the text of the element next to the bar which is the <strong> containing the percentage.

Then we make sure the width is set to 0%, and animate it:

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.