Voting system can be important part of any website, especially if you want to keep track of user ratings. Let’s create a cookie based voting system, similar to YouTube like & dislike buttons (Thumbs up & Thumbs down), which can be applied to any content.
We will assign Unique ID(s) to each voting block, these Unique IDs will play important role here, we will be updating and inserting database records, and identifying user votes based on it. Let’s create a 4 columns table in MySql Database.
This is our CSS, this should go within head tag or in a CSS file.
Paste following HTML code in your page anywhere you want voting system to appear, I have inserted the code inside header <h3> — </h3>. Replace each block ID XXXXXXX with unique number or string, Unique ID should not match with each other.
On page load, we will fetch vote counts from database into <span class="up_votes"></span> and <span class="up_down"></span> elements. Using jQuery.each() we can loop through each voting block to collect Unique IDs. These IDs are required to fetch vote counts for each voting block.
Since we need to fill two values here, it is good idea to fetch JSON data. (See vote_process.php for PHP json_encode() usage).
Take a look at code below:
jQuery Code below is triggered when user clicks Thumbs up or Thumbs down icon. We need to retrieve the class name of clicked element and compare whether vote is like or dislike, then we send Ajax request to vote_process.php using jQuery $.post() along with Unique ID and Vote type. Please go though each comment line in the code to understand the method clearly.
Here’s our complete vote_process.php file. This PHP code retrieves Ajax POST variables from voting system page, and $_POST[“vote”] variable is used to determine what action should be performed next.
Since this is a cookie based voting, script sets a cookie after each user vote and prevents user from voting again until the cookie expires.