Voting system with jQuery, Ajax and PHP.
Wall Script
Follow Me:
Monday, August 03, 2009

Voting system with jQuery, Ajax and PHP.

This post about Dzone like voting system with jQuery, Ajax and PHP. This script helps you to display user votes on blog post. IP address based voting system I hope you like this thanks! Take a look at live demo and give your votes.

Voting system with jQuery, Ajax and PHP.

Download Script     Live Demo

Database Design

Messages Table :
CREATE TABLE messages(
mes_id INT PRIMARY KEY AUTO_INCREMENT,
msg TEXT,
up INT,
down INT);

Voting_IP Table : Storing IP address
CREATE TABLE Voting_IP(
ip_id INT PRIMARY KEY AUTO_INCREMENT,
mes_id_fk INT,
ip_add VARCHAR(40),
FOREIGN KEY(mes_id_fk)
REFERENCES messages(mes_id));
Foreign key tutorial

Voting.php
Contains javascript, PHP and HTML code. $(".vote").click(function(){}- vote is the class name of anchor tag. Using element.attr("id") calling vote button value(messsage Id).
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js
"></script>
<script type="text/javascript">
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);

if (name=='up')
{
$(this).fadeIn(200).html('<img src="dot.gif" />');
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,

success: function(html)
{
parent.html(html);
}
});
}
else
{
$(this).fadeIn(200).html('<img src="dot.gif" />');
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false,

success: function(html)
{
parent.html(html);
}
});
}
return false;
});
});
<script

//HTML Code

<?php
include('config.php');
$sql=mysqli_query($db,"SELECT * FROM messages LIMIT 9");
while($row=mysqli_fetch_array($sql,MYSQLI_ASSOC))
{
$msg=$row['msg'];
$mes_id=$row['mes_id'];
$up=$row['up'];
$down=$row['down'];
?>
<div class="main">
<div class="box1">
<div class='up'>
<a href="" class="vote" id="<?php echo $mes_id; ?>" name="up">
<?php echo $up; ?></a></div>

<div class='down'>
<a href="" class="vote" id="<?php echo $mes_id; ?>;" name="down">
<?php echo $down; ?></a></div>
</div>

<div class='box2' ><?php echo $msg; ?></div>
</div>

<?php } ?>




up_vote.php
Contains PHP code.
<?php
include("config.php");
$ip=$_SERVER['REMOTE_ADDR'];

if($_POST['id'])
{
$id=$_POST['id'];
$id = mysqli_real_escape_string($db,$id);
//Verify IP address in Voting_IP table
$ip_sql=mysqli_query($db,"select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysqli_num_rows($ip_sql);

if($count==0)
{
// Update Vote.
$sql = "update Messages set up=up+1 where mes_id='$id'";
mysqli_query($db, $sql);
// Insert IP address and Message Id in Voting_IP table.
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$id','$ip')";
mysqli_query( $db,$sql_in);
echo "<script>alert('Thanks for the vote');</script>";
}
else
{
echo "<script>alert('You have already voted');</script>";
}

$result=mysqli_query($db,"select up from Messages where mes_id='$id'");
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$up_value=$row['up'];
echo $up_value;

}
?>

down_vote.php
You have to modify up_vote.php code just replace word up to down in SQL statements.

CSS Code:
#main
{
height:80px;
border:1px dashed #29ABE2;
margin-bottom:7px;
width:500px;
}
.box1
{
float:left;
height:80px;
width:50px;
}
.box2
{
float:left;
width:440px;
text-align:left;
margin-left:10px;
height:60px;
margin-top:10px;
font-weight:bold;
font-size:18px;
}
.up
{
height:40px;
font-size:24px;
text-align:center;
background-color:#009900;
margin-bottom:2px;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
}
.down
{
height:40px;
font-size:24px;
text-align:center;
background-color:#cc0000;
margin-top:2px;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
}

config.php
Database configuration file.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

More jQuery and Ajax Tutorials : Click Here
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


119 comments:

  1. Little modification added alert messages.

    else
    {
    echo "<script>alert('You have already voted');</script>";
    }

    ReplyDelete
  2. Another vote system based on jQuery: http://www.vlkomarov.info/projects/jquery/very-simple-rating-system/ - more simple: only positive voting..

    ReplyDelete
  3. Wish I could change my vote.

    ReplyDelete
  4. Thanks

    nice i used it at : http://fcukmylife.us

    ReplyDelete
  5. thanks, it's very useful samples for me. :)

    ReplyDelete
  6. Great piece of work. Thanks.
    Minor changes that may be helpful:
    use same case for the table names as they are created in all the files, particulary up_vote.php and down_vote.php. It seemed to create some problems for me.

    ReplyDelete
  7. how can I display the items on pages in descending order of votes i.e. item with most votes get listed at top ?

    ReplyDelete
  8. Hi, excellent work. I am interested into the same problem like previous user, how to get listed the items over their votes number? The one with the biggest number to be the first and so on... Thanks a lot

    ReplyDelete
  9. @ken
    use ORDER BY up DESC in voting.php

    example:
    include('config.php');
    $sql=mysql_query("SELECT * FROM messages ORDER BY up DESC LIMIT 9");
    while($row=mysql_fetch_array($sql))

    ReplyDelete
  10. hey guys trying to get this right I connected to database but when I try to vote i get the following error. I am kind of a newbie

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in/home/content/g/e/t/getinthegame/html/sportzline/up_vote.php on line 30

    line 30 says
    $result=mysql_query("select down from Messages where mes_id='$id'");

    Any Help?

    ReplyDelete
  11. Hey guys, great work, I will use it in my actual onlineshop project. Thanks!!

    ReplyDelete
  12. you can vote infinitive up votes unless you change
    "Messages" to "Voting_ip" in up_vote.php, compare it to down_vote.php and see the diffrence

    ReplyDelete
  13. Same probleme


    hey guys trying to get this right I connected to database but when I try to vote i get the following error. I am kind of a newbie

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in/home/content/g/e/t/getinthegame/html/sportzline/up_vote.php on line 30

    line 30 says
    $result=mysql_query("select down from Messages where mes_id='$id'");

    Any Help?

    ReplyDelete
  14. i get the same error...

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /homepages/8/d217407391/htdocs/webgroup/donlope/voting/up_vote.php on line 30

    What can we do???

    ReplyDelete
  15. Adrian said...
    cos $sql - are not returned a result.check your query.

    ReplyDelete
  16. "are not returned a result.check your query..."
    I dont understand..

    ReplyDelete
  17. i have been trying to make this code work on my site for one whole week and not been able to start it. All it shows its the title of the script and rest everything else is missing. Yes i checked the config file and have put in correct entries. Can anyone help me with this?

    ReplyDelete
  18. How could you turn the votes into a percentage?

    Example:

    Do you like this?
    Yes: 80% No: 20%

    ReplyDelete
  19. Has anybody modified this so that if you click a thumbs up img the value next to it will go up e.g. youtube thumbs up thumbs down feature

    ReplyDelete
  20. How come everything disappears when I added the jquery script?

    ReplyDelete
  21. in your tutorial dont forget to fix a small mistake

    <*script

    ReplyDelete
  22. How can I modify the script so that the guest/visitors can also add entries to the list ?

    the guest entries should first go to a backed moderation section before appearing on the site

    ReplyDelete
  23. how could this be implementd in wordpress? for one category? it's really good

    ReplyDelete
  24. hello. how protect files included in ajax, like up_vote.php from run outside the script?

    ReplyDelete
  25. Thank you Tamada for sharing with us, it's very usefull and looks so good.
    I find the error that can get some problems, on line 32 replace M letter, with m, from table messages, and will work. $result=mysql_query("select up from Messages where mes_id='$id'");

    ReplyDelete
  26. Oh man first thank for the great work but i dont understand why you take long time and dont answer the commets. I have added the script but not working. Regards!

    ReplyDelete
  27. I need the values in the database.... please can anyone share the tables data... i created the messages table, but its empty...

    ReplyDelete
  28. how does one add messages to the database?

    ReplyDelete
  29. great job very flexible and practical script. I vote up!

    ReplyDelete
  30. very good, its a very nice feature for site.
    i added a link from my ajax examples web site
    www.ajaxshake.com

    ReplyDelete
  31. i get:

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in .../down_vote.php on line 31

    whats wrong? thx

    ReplyDelete
  32. Hi,
    i change your nice code for admin or auther ( blog poster) now when click for vote admin if in page LIMIT = 9 show 9 alert box ( 'You have already voted'), how to fix this?

    Thanks

    ReplyDelete
  33. Srinivas Tamada !

    i change your nice code for admin or auther ( blog poster) now when click for vote admin if in page LIMIT = 9 show 9 alert box ( 'You have already voted'), how to fix this?

    Can you help me >

    ReplyDelete
  34. wow...this is amazing...thanks for sharing this....thanks...

    ReplyDelete
  35. I just try to use your voting (and is great) but when you put it on mod_rewrite website... doesn't work. I have no ideea why. I taste the same page with or without mod_rewrite activated. When was without the script was working great, when mod_rewrite was activated... no. So, i someone have anyideea why...pls tell me :)

    ReplyDelete
  36. Yes, I cam getting the same problem with mod_rewrite. Script works flawless with a query string, .e.g. yourdomain.com/index.php?sort=new&time=day, but if you have mod_rewrite to use "pretty" urls, like yourdomain.com/new/day it stops working. Anyone know the cause?

    ReplyDelete
  37. Try capitalizing Messages in DB

    ReplyDelete
  38. Excellent script and very easy ro implement thanks !!! >.<

    ReplyDelete
  39. i had a problem
    after all database connected
    i have voting.php page showing only

    Voting with jQuery, Ajax and PHP

    ReplyDelete
  40. nice, how you added voting.php to your blog, since it is blogger hosting know, can you give a reply

    ReplyDelete
  41. same problem


    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/content/19/6549019/html/bb/poll/up_vote.php on line 30

    ReplyDelete
  42. Thank you for sharing this information with us.

    ReplyDelete
  43. What database to use?

    ReplyDelete
  44. Useful tutorial. But I saw the voting with social networks. I mean user came to the site with voting and there are several items on which he can vote with his Facebook and Twitter accounts. How can be the similar thing done with the code in this article?

    ReplyDelete
  45. hi

    first of all thanks for a grate tut... but it has error... in my side and i seen more than 5-6 comment with same error



    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/ajay/public_html/kiransteel.com/voting/down_vote.php on line 12

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/ajay/public_html/kiransteel.com/voting/down_vote.php on line 31


    and please do not use " Message " The capital m M" it will create when it is on server side...

    thanks and wait for your solution ...

    ReplyDelete
  46. Really like your blog ,because are very interesting articles here ,thanks for that.

    ReplyDelete
  47. @Jocurl: mod_rewrite fix (well works for me)

    full path in ajax:
    url: "http://somedomain.com/up_vote.php",

    ReplyDelete
  48. great script! i change your nice code for admin on my wordpress.

    ReplyDelete
  49. Thank you for the great tutorial!
    I have some questions:
    - Rather than clicking on the number, how to click on an image to vote?
    - Is there a way to show the net vote, meaning:
    net vote= positive votes-negative votes
    - Is there a way to sort table by net vote, after the user clicks on up or down?
    Thanks,

    ReplyDelete
  50. He still doesn't fix his problem yet, isn't it?

    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/ajay/public_html/kiransteel.com/voting/down_vote.php on line 12

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/ajay/public_html/kiransteel.com/voting/down_vote.php on line 31

    .....

    ReplyDelete
  51. Hey, I am developing an election voting system votes of candidates goes to db mysql and should show a graph.please help..thnx and more power..

    ReplyDelete
  52. This blog is very interesting for me and others ,I will return very soon for other items,thank you very much.

    ..and thanks for script :)

    ReplyDelete
  53. Thanks for the script is great.
    But how can I not to vote several times those with dynamic ip.
    meaning they can only vote once a day?
    Thanks.

    ReplyDelete
  54. 2 marian

    I changed the IP to user ID (from the Users table)

    ReplyDelete
  55. So yes they go.
    but only those registered voted.
    I need to vote and visitors.

    ReplyDelete
  56. Great script - thanks for this (although there are one or two syntax that needed to be resolved, as mentioned in previous comments).

    For the guys having problems using it with mod_rewrite, I had the same problem but managed to resolve by changing the js in the header to:

    url: "/up_vote.php",

    The forward slash ensures it can find the up_vote script when using slashes in the urls (presuming up_vote,php is in the root).

    ReplyDelete
  57. Brother, i want to separate time for each vote of each user. eg. time separate 4 hour for each user vote time. how to do it. please description to me.

    ReplyDelete
  58. ERROR in up_vote.php

    line:
    $sql_in = "insert into messages (mes_id_fk,ip_add) values ('$id','$ip')";

    should be:
    $sql_in = "insert into voting_ip (mes_id_fk,ip_add) values ('$id','$ip')";

    ReplyDelete
  59. This blog is very interesting for me and others ,I will return very soon for other items,thank you very much.

    ..and thanks for script :)

    ReplyDelete
  60. Maybe a stupid questiong.. how does the config.php look like? what is the host, username and passwd syntax

    ReplyDelete
  61. You add a type of score, 1+ o 1- , because spammers o kakers attack about this ¬¬..
    $score = (int) $_POST["score"];
    if($score > 1) die("No more 1 Vote");

    ReplyDelete
  62. it's a nice script, just in file download there on bugs about the name of the table on:up_vote.php

    $sql_in = "insert into Messages (mes_id_fk,ip_add) values ('$id','$ip')";

    ReplyDelete
  63. There is an error:

    'Messages' should be replaced by 'messages' Otherwise it does not work properly

    Thanks for the tutorial, i have it working, if someone has any queries, contact me clicking on my name

    ReplyDelete
  64. Works great, had to change some things to fit my sites database; but honestly one of the best scripts I've used... efficient and easy to edit!

    Thank you!

    ReplyDelete
  65. thnx for tutorial.it help in my project.thnx

    ReplyDelete
  66. Hi,
    Nice ... Have u noticed that the vote is not updated after you hit refresh . Eventhough you have added "cache:false" in your ajax script , caching takes place.Please resolve the issue.

    ReplyDelete
  67. Thanks, It's easy and useful.

    ReplyDelete
  68. I like this script. Please add one more box showing rank.

    ReplyDelete
  69. Tested a script on denwer does not work. On a hosting has established, css-styles are displayed only. The script in an initial code is displayed, but does not work. In what maybe a problem prompt please?

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

    ReplyDelete
  71. I would like to have it as a plugin for my WordPress blog..

    can anyone convert it to a WordPress plugin?

    ReplyDelete
  72. this is very cool, i just've adecuate to my especifications.. thanks a lot

    ReplyDelete
  73. How to get the local ip address when the systems are in LAN or intranet.

    ReplyDelete
  74. it is quiet good code but one thing strikes me is that when i click down vote ,,i get down votes suppose i want to give upvote after sometimes! that is not seem possible because you have already voted,,sometimes a user can like to vote again if he feels upvote! can you catch my point as FB has LIKE and Dislike with same button!

    ReplyDelete
  75. Great script! thanks for this.
    Quick question, if i want to show the score instead ($up - $down) how can i do that?
    Thanks!

    ReplyDelete
  76. I have connected to the DB but I only get the header and nothing else on the screen

    ReplyDelete
  77. I have connected to the DB but I only get the header and nothing else on the screen

    ReplyDelete
  78. I learned lot from your blog. But I think it's time for you to update your codes using mysqli_* since they will remove the mysql_* soon. If you do update your codes lot of new visitors can benefit from that. Anyway thank you for the greate job you do

    ReplyDelete
  79. $ip=$_SERVER['REMOTE_ADDR'];

    In up_vote.php, the above code is calling the ip address.

    If i want to call my UserID? What code should i write :( ? Pls help Thanks

    ReplyDelete
  80. i too am getting nothing but the header as well...

    ReplyDelete
  81. I got it to work now how can i have more than one on the same page??!?1

    ReplyDelete
  82. this is hard for me to understand :P ! i talk about the script .

    ReplyDelete
  83. Does this script can be applied in rating images (individually)?. Thank you.

    ReplyDelete
  84. thnq u for sharing this post

    ReplyDelete
  85. the voting for some reason doesnt workk on me...

    ReplyDelete
  86. Nice script. Thank you.
    Does it work with MAMP? Everything works good but i see no numbers of voting. I have indexed mes_id_fk and related with mes_id in messages. I think i have to change mes_id in msg_id in all the voting scripts, because i have some other script.

    ReplyDelete
  87. The script is quite good, but there is a problem with php files up_vote.php and down_up.php on line number 6,stating undefined index 'id'. The tutorial is great,but I would really be obliged,if you help me in tackling why this problem is occurring,since I want to use voteup and votedown button in my project.Please help me!

    ReplyDelete
  88. The tutorial is really great,I downloaded and made database connection the way u've mentioned ,but there is an error with the php files up_vote.php and down_vote.php on line number 6, stating undefined index id,and I'm unable to understand its occurrence,since I'm a newbie,I want to make use of vote up and vote down buttons in my project,PLZ HELP ME SOLVE THIS ERROR!!

    ReplyDelete
  89. the number of votes is not getting incremented after clicking on the button...!!!

    ReplyDelete
  90. Awesome work !!! Thanks :) Just what I was looking for.

    @Rakhi Dhavale if the numbers are not incrementing maybe is because the query that increments the value of the up and down is not working properly.

    Try sending it directly through the mysql console replacing the '$id' value with a number (2 for example) and check using phpmyadmin if the value incremented. I am refering to this query "update Messages set up=up+1 where mes_id='$id" inside the up_vote.php file.

    Hope it helps.

    ReplyDelete
  91. Can someone help me with this please ......

    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /home/mmaigbo/public_html/vote/up_vote.php on line 12

    ReplyDelete
  92. down_vote.php at lint 19 and 20

    $sql_in = "insert into voting_ip (mes_id_fk,ip_add) values ('$id','$ip')";
    mysql_query( $sql_in);

    up_vote.php at lint 19 and 20

    $sql_in = "insert into messages (mes_id_fk,ip_add) values ('$id','$ip')";
    mysql_query( $sql_in);


    is this correct.... have already solve some couple of problems but now votes are not updating

    ReplyDelete
  93. Thanks for this code, it's very helpful.

    ReplyDelete
  94. It shows error

    Deprecated: mysql_escape_string(): This function is deprecated; use mysql_real_escape_string() instead. in up_vote.php on line 9

    ReplyDelete
  95. I was looking for this script. Thanks :)

    ReplyDelete
  96. but when my friend under similar network (same IP Address), he can't do vote. Any solution for this condition?

    ReplyDelete
  97. Notice: Undefined index: id in C:\wamp\www\voting\voting\down_vote.php on line 6
    how to solve it?

    ReplyDelete
  98. Who can add the code for PHP 7, mysqli ?

    ReplyDelete
  99. ERROR in up_vote.php

    line:
    $sql_in = "insert into messages (mes_id_fk,ip_add) values ('$id','$ip')";

    should be:
    $sql_in = "insert into voting_ip (mes_id_fk,ip_add) values ('$id','$ip')";

    ReplyDelete
  100. Warning: mysqli_connect(): (28000/1045): Access denied for user 'targetla_kjuser'@'localhost' (using password: YES) in /home/panekham/public_html/kuanjailao.com/config.php on line 6

    Warning: mysql_query(): Access denied for user 'root'@'localhost' (using password: NO) in /home/panekham/public_html/kuanjailao.com/voting.php on line 152

    Warning: mysql_query(): A link to the server could not be established in /home/panekham/public_html/kuanjailao.com/voting.php on line 152

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/panekham/public_html/kuanjailao.com/voting.php on line 153

    ReplyDelete

Make in India