Skip to main content

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.

  `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) {
    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)

# connect mysql db
$query = mysql_query(
  'SELECT id, first_name, last_name, film_info, vote 
  FROM  voting
  LIMIT 0 , 15');
<!doctype html>
<html lang="en">
  <meta charset="UTF-8" />
  <title>jQUery Voting System</title>
  <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 class="post"><!-- post data -->
        <h2><?php echo $row['first_name'].' '.$row['last_name']?></h2>
        <p><?php echo $row['film_info'] ?></p>
    <?php endwhile?>
  <?php dbConnect(false); ?>


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 */
  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}


<script src=""></script>
  // ajax setup
    url: 'ajaxvote.php',
    type: 'POST',
    cache: 'false'

  // any voting button (up/down) clicked event
    var self = $(this); // cache $this
    var action ='action'); // grab action data up/down 
    var parent = self.parent().parent(); // grab grand parent .item
    var postid ='postid'); // grab post id from data-postid
    var score ='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
        // change vote up button color to 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
        // change vote up button color to red
        // send ajax request
        $.ajax({data: {'postid' : postid, 'action' : 'down'}});

      // add disabled class with .item


# start new session
  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
        UPDATE voting
        SET vote = '{$vote}'
        WHERE id = '{$postId}' ");

      # set session with post id as true
      $_SESSION['vote'][$postId] = true;
      # close db connection


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

    1. please can u send de procedure to install it

  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.


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

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


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


    how to set this ? "201" where in table hm..

  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.

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

  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.

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

    2. How did you fix the problem? :)

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

  7. Had to add:
    on Line 9 in ajaxvote.php, otherwise votes didn't stick.

  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

  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.

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

    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.

  11. Hi Resalat,

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

  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.

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

    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.


  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.

  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.

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

  17. demo & download does not work

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

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

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

  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.

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

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

  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.

  25. This comment has been removed by the author.

    1. This comment has been removed by the author.

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

  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

  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

  29. please solves this problems love commints

  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.

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

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

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

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

  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

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

  37. I have read your blog its very attractive and impressive. I like it your blog.

    PHP Training in chennai | PHP Training Course

    PHP Training in chennai | Online PHP Course

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

  39. 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

  40. I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you. I like play game five nights at freddy’s 4, game word cookies game , game hill climb racing 2 , hotmail login, and u? I hope people visit my website.

  41. One can vote after every refresh on same post. it will great if one ip can vote only one time.

  42. With the advent of technology, people have moved ahead in terms of standard of living and day to day life, but we have accompanied many unwanted things as well. One of them is stress! There is no proper definition of stress but those into science define it as unrelated response of human body to external force. Gurgaon Escorts

  43. I had a problem with the arrow action but I finally figured it out after looking at your code. Check out my project where I did a voting system inside Laravel.

  44. The blog or and best that is extremely useful to keep I can share the ideas of the future as this is really what I was looking for, I am very comfortable and pleased to come here. Thank you very much.
    animal jam | five nights at freddy's | hotmail login


  45. Hi Everyone My Self Urvasi From Gurgaon 24x7 Girls Service Escorts provider We Providing Indian Russian Model Call Girls service There Are desirable
    Escorts in Gurgaon
    Gurgaon Escorts
    Escorts Service in Gurgaon
    Gurgaon Escorts Service

  46. Thanks a lot! Awesome tutorial. Work like a charm!!!!


Post a Comment

Popular posts from this blog

Multiple File Upload with Progress Bar using PHP & jQuery

Some days age I have created a post that deals with How we can upload file with progress bar using php and jQuery . Some of my readers asked me how we can upload multiple files with progress bar. In this post I am going to show you how we can upload multiple files with progress bar. We can upload multiple files with progress bar exactly same way as I shown previous. But we need to do some modification with our file upload form and our php script to handle multiple files.

Multiple File Upload with PHP

Sometimes we need to allow our users to upload multiple file upload. On my previous post I was shown the basic of simple file upload with PHP. Today I am going to show you how to allow users to upload multiple files. It is almost similar like simple file upload but we need to do some modification with html markup and php code . multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. Now I am going to show you how to upload multiple file with PHP and basic HTML form.

File Upload with Progress Bar using jQuery and PHP

In this post you will learn how to create a AJAX file uploading system with progress bar using jQuery and PHP. For this purpose we will going to use jQuery Form Plugin . It is a easy to use and powerful jQuery AJAX form submitting plugin. It supports XMLHttpRequest Level 2 and iframe file transportation. That's why it will work for both old and new browsers.