Dynamic Voting System with jQuery, PHP and MySQL

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.




Live Demo Download Source

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

60 comments:

  1. Perfect been looking for this for a while :) ACES

    ReplyDelete
    Replies
    1. please can u send de procedure to install it

      Delete
  2. Hello,

    How to save the vote? I mean i create new item via insert in DB, start from 0 and i test to vote. But, when i refresh the page its back to 0. This test in local only so far.

    Thanks

    ReplyDelete
    Replies
    1. Take a look on the ajaxvote.php file. It describe everything about update votes.
      mysql_query("
      UPDATE voting
      SET vote = '{$vote}'
      WHERE id = '{$postId}' ");

      Delete
    2. Its still back again if the page refresh or reload, any clue? lil bit stuck in here.

      Thanks

      Delete
    3. Doesn't work here either. Votes aren't being updated in database.

      Delete
    4. BUT CANT UPDATE !!!!!! AHHHHHHH PLS FIX IT

      Delete
  3. ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=201 ;
    how to set this ? "201" where in table hm..

    ReplyDelete
  4. Hi Resalat..
    there is a typo in the download package ->config.php define('DB_HOST', 'locahost'); instead of define('DB_HOST','localhost'); "L" was missing nevertheless i coldnt make it vote either ..values in the database do not change.
    cheers
    martin

    ReplyDelete
  5. Hi Resalat..
    me again .. your voting system works now with the "dbConnect(); in ajaxvote.php"
    Thanks for debugging
    Martin

    ReplyDelete
  6. Hello Resalat,
    Thank you for these wonderful scripts, I'm facing the same issue like, it not updating the record on the database, I have the fixed the missing L and I can see dbConnect(); but still not functioning.. can you please advise.

    ReplyDelete
    Replies
    1. I found my mistake, it works now.. thank you again Resalat for the wonderful script.

      Delete
    2. How did you fix the problem? :)

      Delete
    3. for me it was the matter of correcting variable names for my script, once done properly all was functional.

      Delete
  7. Had to add:
    dbConnect();
    on Line 9 in ajaxvote.php, otherwise votes didn't stick.

    ReplyDelete
  8. Hi Resalat! is there away we can edit the code to vote only once, i mean once you vote once you cannot vote on other items..or using ip, we can validate if he/she voted already

    ReplyDelete
  9. this is not the same. Reddit you can click the upvote button to remove your vote, or downvote to change it from +1 to -1. This code can do none of that, and locks in your vote forever.

    ReplyDelete
  10. Hello, I just hope someone will read my message ^^'.

    This looks awesome, I want to use this for my website. I created the table on my MySQL + uploaded the page on my server. I take a looks on the post structure, I know there are some variables. But where I can add titles and descriptions and this for each post ? And how can I add post ?

    I'm a beginner but this is too hard for me. The tutorial doesn't show how to use, sorry but I think it's a little shame for those like me who don't have experience...

    ReplyDelete
    Replies
    1. Sorry but I just found it, it's a SQL request as I supposed but I didn't know the command until now >__>. Sorry for my previous message.

      Delete
  11. Hi Resalat,

    The sql table is only saving the first vote, but not the rest. Do you know a way to fix that?

    ReplyDelete
  12. Hello thanks a lot for this good work.
    I am not so good at Php. My most dificult problem is how to add and image to this voting system, thanks a lot.

    ReplyDelete
  13. Great code. Thanks! I have one suggestion in the query to include all entries and order by descending:

    $query = mysql_query(
    'SELECT id, first_name, last_name, film_info, vote
    FROM voting
    ORDER BY vote DESC');

    ReplyDelete
    Replies
    1. Hey Blake,

      Do you know how I would be able to order posts in order of their vote? So the highest voted posts is at the top of the list.

      Thanks,
      Rob

      Delete
  14. Hi Resalat, thanks for your good work.

    Could you plese check the ZIP file. I found errors in packed ZIP file with source code.

    ReplyDelete
  15. Problem is that as soon as they log out and log back in or clear their cookies they can vote again. This will work as long as you don't mind people being able to game your system.

    ReplyDelete
  16. Replies
    1. File updated! Thanks for your notification!

      Delete
  17. demo & download does not work

    ReplyDelete
  18. Arrow is not getting visible in IE until mouse over.

    ReplyDelete
  19. Hello! I love the style of this, but how could you let users add more to the list?

    ReplyDelete
  20. Dear Brother This code have done helpful. thanks and Go ahead.

    ReplyDelete
  21. I am having issues like every one else where it does not update the vote on the server or as an Ifram from a different server.

    Line 9 has the DBConnect(); and all connection strings are working but it will not save a vote when a user clicks on the up or down arrow.

    ReplyDelete
  22. i've got this working locally (localhost) but when i upload to my server it stops working (cookie/session) issue ??? Thoughts?

    ReplyDelete
  23. At-last it is working in my web "http://bdshowbiz.com/vote"
    I just replace 'locahost' by 'localhost' in config.php,
    and add dbConnect(); in line 10 on ajaxvote.php
    Thank you Resalat Haque

    ReplyDelete
  24. Can this script add the function to load data as you scroll down? I've tried to use this script with jscroll but the voting function didn't work then. I want to speed up the page loading and want to load data from mysql dynamically but to retain the voting function. I'd like to hire someone to do this.

    ReplyDelete
  25. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  26. I get this error... :-( Deprecated function: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead i dbConnect() (line 13 in jquery-voting-system/config.php).

    And I got PHP 5.5..

    ReplyDelete
  27. Hello. I used for my main page and work perfect. But I want also use for another page of my web and there is after scrolling displayed again all content from first page. I have on 2nd page another $sql query but code still take from 1st

    ReplyDelete
  28. Notice: Undefined variable: link in C:\xampp\htdocs\jewel\jquery-ajax-comment-system\function.php on line 11

    Warning: mysql_close() expects parameter 1 to be resource, null given in C:\xampp\htdocs\jewel\jquery-ajax-comment-system\function.php on line 11

    ReplyDelete
  29. please solves this problems love commints

    ReplyDelete
  30. the problem everyone is having with votes not sticking is a simple fix. change $_POST to $_REQUEST in ajaxvote.php and vote update sticks in database.

    ReplyDelete
  31. Hi, the up and down are not working. Pls help

    ReplyDelete
  32. The zip file is not working,can anyone help me ?

    ReplyDelete
  33. hello i cant connect it to the database can anyone help me

    ReplyDelete
  34. please can anyone send me the guideline as how to install it. am getting to much errors

    ReplyDelete
  35. Dapatkan disini , karena Obat Pelangsing slimming Capsule Di Apotik belum tersedia , karena slimming capsule tidak di jual di sembarang temapat termasuk di apotik pun tujuannya untuk menjaga ke aslian produk tersebut, karena sekarang banyak perusahaan yang meniru produk produk herbal sehingga herbal yang asli khasiatnya bisa di rusak oleh produk yang palsu. Untuk itu hati hati dengan slimming capsule

    and obat vig power capsule

    ReplyDelete
  36. The content is well written with detailed information. Great thanks for the awesome share. buy online votes

    ReplyDelete
  37. do i have to write all this code in a single file eith extension .php?

    ReplyDelete
  38. I can't accept, in light of what I see on TV, that anybody can believe any result after the way these cards have been checked, stacked and modified. After this control, the cards are harmed merchandise. Indeed, even paper and stock card makers would have a troublesome time deciding voter plan. Regardless of the possibility that the individuals who have taken care of the describe so far were supplanted by unprejudiced laymen in the court framework, very little more objectitve reality will be come to with respect to who voted in favor of whom. Like a simple-majority voting system

    ReplyDelete

Go to top