In this post you will learn how to build a voting system with jQuery, Ajax, PHP and MySQL. Votes will be update at real time and store to the database table with out refreshing or redirecting page. This post is inspired by Reddit and Stack Overflow voting system. This system will allow users to vote up or vote down every single post at once in a session.

Database Design

At first we need to create a database table called voting. Actually this table stores all information like post contents and voting information.

CREATE TABLE IF NOT EXISTS `voting` ( `id` int(5) NOT NULL AUTO_INCREMENT, `first_name` varchar(45) NOT NULL, `last_name` varchar(45) NOT NULL, `film_info` text NOT NULL, `vote` int(8) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) );

Database Configurations and Connection

This configuration file is responsible for making DB connection. You need to do little bit modify it.

# db configurations define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', 'root'); define('DB_NAME', 'mydb'); # db connect function dbConnect($close=true){ global $link; if (!$close) { mysql_close($link); return true; } $link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Could not connect to MySQL DB ') . mysql_error(); if (!mysql_select_db(DB_NAME, $link)) return false; }

PHP & HTML (Retrieve DB Recodes)

<?php include('config.php'); # connect mysql db dbConnect(); $query = mysql_query( 'SELECT id, first_name, last_name, film_info, vote FROM voting LIMIT 0 , 15'); ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>jQUery Voting System</title> </head> <body> <div class="wrap"> <?php while($row = mysql_fetch_array($query)): ?> <div class="item" data-postid="<?php echo $row['id'] ?>" data-score="<?php echo $row['vote'] ?>"> <div class="vote-span"><!-- voting--> <div class="vote" data-action="up" title="Vote up"> <i class="icon-chevron-up"></i> </div><!--vote up--> <div class="vote-score"><?php echo $row['vote'] ?></div> <div class="vote" data-action="down" title="Vote down"> <i class="icon-chevron-down"></i> </div><!--vote down--> </div> <div class="post"><!-- post data --> <h2><?php echo $row['first_name'].' '.$row['last_name']?></h2> <p><?php echo $row['film_info'] ?></p> </div> </div><!--item--> <?php endwhile?> </div> <?php dbConnect(false); ?> </body> </html>

Styling

We need to do some styling for post contents and vote buttons. In here, I used Font Awesome for style up vote up and down buttons. If you want you can use image background as you like.

/* voting style */ .vote-span{ width: 60px; float: left; margin: 5px 0; } .vote, .vote-score{ clear: both; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2); cursor: pointer; text-align: center; color: #333; font-size: 1.8em; font-weight: bold; } .vote-score{cursor: text}

jQuery

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> $(document).ready(function(){ // ajax setup $.ajaxSetup({ url: 'ajaxvote.php', type: 'POST', cache: 'false' }); // any voting button (up/down) clicked event $('.vote').click(function(){ var self = $(this); // cache $this var action = self.data('action'); // grab action data up/down var parent = self.parent().parent(); // grab grand parent .item var postid = parent.data('postid'); // grab post id from data-postid var score = parent.data('score'); // grab score form data-score // only works where is no disabled class if (!parent.hasClass('.disabled')) { // vote up action if (action == 'up') { // increase vote score and color to orange parent.find('.vote-score').html(++score).css({'color':'orange'}); // change vote up button color to orange self.css({'color':'orange'}); // send ajax request with post id & action $.ajax({data: {'postid' : postid, 'action' : 'up'}}); } // voting down action else if (action == 'down'){ // decrease vote score and color to red parent.find('.vote-score').html(--score).css({'color':'red'}); // change vote up button color to red self.css({'color':'red'}); // send ajax request $.ajax({data: {'postid' : postid, 'action' : 'down'}}); }; // add disabled class with .item parent.addClass('.disabled'); }; }); }); </script>

ajaxvote.php

include('config.php'); # start new session session_start(); dbConnect(); if ($_SERVER['HTTP_X_REQUESTED_WITH']) { if (isset($_POST['postid']) AND isset($_POST['action'])) { $postId = (int) mysql_real_escape_string($_POST['postid']); # check if already voted, if found voted then return if (isset($_SESSION['vote'][$postId])) return; # connect mysql db # query into db table to know current voting score $query = mysql_query(" SELECT vote from voting WHERE id = '{$postId}' LIMIT 1" ); # increase or dicrease voting score if ($data = mysql_fetch_array($query)) { if ($_POST['action'] === 'up'){ $vote = ++$data['vote']; } else { $vote = --$data['vote']; } # update new voting score mysql_query(" UPDATE voting SET vote = '{$vote}' WHERE id = '{$postId}' "); # set session with post id as true $_SESSION['vote'][$postId] = true; # close db connection } } } dbConnect(false);