9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
Monday, August 3, 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=mysql_query("SELECT * FROM messages LIMIT 9");
while($row=mysql_fetch_array($sql))
{
$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 = mysql_escape_String($id);
//Verify IP address in Voting_IP table
$ip_sql=mysql_query("select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysql_num_rows($ip_sql);

if($count==0)
{
// Update Vote.
$sql = "update Messages set up=up+1 where mes_id='$id'";
mysql_query( $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')";
mysql_query( $sql_in);
echo "<script>alert('Thanks for the vote');</script>";
}
else
{
echo "<script>alert('You have already voted');</script>";
}

$result=mysql_query("select up from Messages where mes_id='$id'");
$row=mysql_fetch_array($result);
$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;
}

More jQuery and Ajax Tutorials : Click Here
Comments
{ 111 comments }
mohamadreza said...

simple and cool

Srinivas Tamada said...

Little modification added alert messages.

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

Hamaelleon said...

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

Anonymous said...

Wish I could change my vote.

Anonymous said...

good

KanSagous said...

Thanks

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

ali said...

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

Aniruddha said...

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.

payam said...

very nice
thanks

Anonymous said...

fghj

Anonymous said...

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

ken the tech said...

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

Anonymous said...

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

Anonymous said...

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?

Webdesign berlin said...

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

Anonymous said...

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

Anonymous said...

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?

infopediaonlinehere said...

its amazing...you are great dude

Adrian said...

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

Dezigo said...

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

Napasov said...

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

Anonymous said...

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?

Jasmine said...

How could you turn the votes into a percentage?

Example:

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

Anonymous said...

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

Abhisek said...

A very detailed and helpful tutorial indeed. Loved it. I made a collection of all such tutorials and scripts (including this one) at 11 PHP Voting Scripts and Tutorials. I hope it would be helpful to many. :-)

Anonymous said...

How come everything disappears when I added the jquery script?

Anonymous said...

in your tutorial dont forget to fix a small mistake

<*script

Farha said...

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

marwa soft said...

thanks alot

developing said...

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

Den said...

Will try it...

Anonymous said...

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

dan said...

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

Anonymous said...

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!

dskanth said...

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

Anonymous said...

how does one add messages to the database?

Anonymous said...

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

Anonymous said...

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

Anonymous said...

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

Anonymous said...

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

Anonymous said...

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 >

web design said...

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

Jocuri said...

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

Anonymous said...

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?

Anonymous said...

Try capitalizing Messages in DB

Guillermo Garcia said...

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

bidur said...

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

Voting with jQuery, Ajax and PHP

Anonymous said...

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

Anonymous said...

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

Srinivas Tamada said...

Please check the SQL query

web developers said...

Thank you for sharing this information with us.

Rakii said...

What database to use?

web forms said...

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?

ajay said...

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

jocuri barbie said...

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

Hoxxy said...

@Jocurl: mod_rewrite fix (well works for me)

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

Jocuri online said...

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

Anonymous said...

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,

n_u_n_u said...

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

.....

Anonymous said...

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

Jocuri Online said...

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

marian said...

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.

Valery said...

2 marian

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

marian said...

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

The Best Way to... said...

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

Anonymous said...

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.

Anonymous said...

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

Free Online Games said...

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

Marcel Kraan said...

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

alan0994 said...

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

Anonymous said...

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

josema said...

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

Aidan said...

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!

sunny said...

thnx for tutorial.it help in my project.thnx

Blogzpoint said...

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.

Zuma said...

Thanks!

Sau Hi said...

Thanks, It's easy and useful.

Anonymous said...

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

Admin said...

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?

Admin said...
This comment has been removed by the author.
samad said...

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

can anyone convert it to a WordPress plugin?

Anh Tuấn said...

Thanks a lot. I will try it.

Francisco Briones said...

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

Mayank said...

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

ramesh said...

nice and esay code thanks

Anonymous said...

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!

Hardane said...

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

Anonymous said...

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

Anonymous said...

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

Anonymous said...

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

Anonymous said...

$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

sally said...

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

mike said...

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

poolet said...

Thanx

Jocuri said...

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

yakarbey said...

thank you

web dizajn said...

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

borna said...

thnq u for sharing this post

Βαγγέλης Ογανεσωφ said...

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

CucKam said...

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.

Rakhi Dhavale said...

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!

Rakhi Dhavale said...

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

Rakhi Dhavale said...

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

Alexis Molina Aragon said...

Muchas gracias :)

Andrew said...

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.

Vincent Nwaikwu said...

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

Vincent Nwaikwu said...

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

Lachit said...

Thanks for this code, it's very helpful.

Anonymous said...

COOL I like it

vish said...

It shows error

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

Elvira Santos said...

It's very helpful. Thanks a lot!

Post a Comment