I received a email request from my reader that asked to me how to implement Youtube like rating with Jquery. It is so nice with quick bar results, So that I had designed a simple script with PHP,Jquery and Ajax. Sure you will like it. Live demo
Download Script Live Demo
Database Design
Messages Table :
CREATE TABLE messages(
id INT PRIMARY KEY AUTO_INCREMENT,
message TEXT,
up INT,
down INT);
id INT PRIMARY KEY AUTO_INCREMENT,
message TEXT,
up INT,
down INT);
Contains javascript, PHP and HTML code. $(".like").click(function(){}- link is the class name of anchor tags(Like and Dislike). Using element.attr("id") calling button name and value((messsage Id)). Notice here anchor tag names(up and down).
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".like").click(function()
{
var id=$(this).attr("id");
var name=$(this).attr("name");
var dataString = 'id='+ id + '&name='+ name;
$("#votebox").slideDown("slow");
$("#flash").fadeIn("slow");
$.ajax
({
type: "POST",
url: "rating.php",
data: dataString,
cache: false,
success: function(html)
{
$("#flash").fadeOut("slow");
$("#content").html(html);
}
});
});
// Close button action
$(".close").click(function()
{
$("#votebox").slideUp("slow");
});
});
</script>
//HTML Code
<a href="#" class="like" id="1" name="up">Like</a>
--
<a href="#" class="like" id="1" name="down">Dislike</a>
<div id="votebox">
<span id='close'><a href="#" class="close">X</a></span>
<div id="flash">Loading........</div>
<div id="content">
</div>
</div>
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".like").click(function()
{
var id=$(this).attr("id");
var name=$(this).attr("name");
var dataString = 'id='+ id + '&name='+ name;
$("#votebox").slideDown("slow");
$("#flash").fadeIn("slow");
$.ajax
({
type: "POST",
url: "rating.php",
data: dataString,
cache: false,
success: function(html)
{
$("#flash").fadeOut("slow");
$("#content").html(html);
}
});
});
// Close button action
$(".close").click(function()
{
$("#votebox").slideUp("slow");
});
});
</script>
//HTML Code
<a href="#" class="like" id="1" name="up">Like</a>
--
<a href="#" class="like" id="1" name="down">Dislike</a>
<div id="votebox">
<span id='close'><a href="#" class="close">X</a></span>
<div id="flash">Loading........</div>
<div id="content">
</div>
</div>
rating.php
Contains PHP code. If name = up it will update UP else DOWN
<?php
include("db.php");
if($_POST['id'])
{
$id=mysql_escape_String($_POST['id']);
$name=mysql_escape_String($_POST['name']);
// Vote update
mysql_query("update messages set $name=$name+1 where id='$id'");
// Getting latest vote results
$result=mysql_query("select up,down from messages where id='$id'");
$row=mysql_fetch_array($result);
$up_value=$row['up'];
$down_value=$row['down'];
$total=$up_value+$down_value; // Total votes
$up_per=($up_value*100)/$total; // Up percentage
$down_per=($down_value*100)/$total; // Down percentage
//HTML output
echo '<b>Ratings for this blog</b> ( '.$total.' total)
Like :'.$up_value.'
<div id="greebar" style="width:'.$up_per.'%"></div>
Dislike:'.$down_value.'
<div id="redbar" style="width:'.$down_per.'%"></div>';
}
?>
include("db.php");
if($_POST['id'])
{
$id=mysql_escape_String($_POST['id']);
$name=mysql_escape_String($_POST['name']);
// Vote update
mysql_query("update messages set $name=$name+1 where id='$id'");
// Getting latest vote results
$result=mysql_query("select up,down from messages where id='$id'");
$row=mysql_fetch_array($result);
$up_value=$row['up'];
$down_value=$row['down'];
$total=$up_value+$down_value; // Total votes
$up_per=($up_value*100)/$total; // Up percentage
$down_per=($down_value*100)/$total; // Down percentage
//HTML output
echo '<b>Ratings for this blog</b> ( '.$total.' total)
Like :'.$up_value.'
<div id="greebar" style="width:'.$up_per.'%"></div>
Dislike:'.$down_value.'
<div id="redbar" style="width:'.$down_per.'%"></div>';
}
?>
Complete Voting Tutorial with IP storing.
Voting system with jQuery, Ajax and PHP.
CSS
#votebox
{
border:solid 1px #dedede; padding:3px;
display:none;
padding:15px;
width:700px;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
}
#greebar
{
float:left;
background-color:#aada37;
border:solid 1px #698a14;
width:0px;
height:12px;
}
#redbar
{
float:left;
background-color:#cf362f;
border:solid 1px #881811;
width:0px;
height:12px;
}
#close
{
float:right; font-weight:bold;
padding:3px 5px 3px 5px;
border:solid 1px #333;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
}
{
border:solid 1px #dedede; padding:3px;
display:none;
padding:15px;
width:700px;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
}
#greebar
{
float:left;
background-color:#aada37;
border:solid 1px #698a14;
width:0px;
height:12px;
}
#redbar
{
float:left;
background-color:#cf362f;
border:solid 1px #881811;
width:0px;
height:12px;
}
#close
{
float:right; font-weight:bold;
padding:3px 5px 3px 5px;
border:solid 1px #333;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
}
jQuery in Action, Second Edition
nice, very very nice, but you can put to vote only once by ip
ReplyDeleteOho, when I asked you if you could do this, I didn;t expect you'll make it so fast and so cool!
ReplyDeleteThank you very much! It's just great!
needs lots of improvement. This wont work on heavy servers.
ReplyDeletehey nice thing and yaa valsis is ryt .. u should try to modify the code so that it takes only 1 input from the user .. in this we can give multiple so not a perfect one for a rating thing
ReplyDeleteNice, really nice, as usual
ReplyDeletevery good post but I'm with "ValsiS" about voting by ip address.
ReplyDeleteNice and Awesome as usually.
ReplyDeleteThanks.
Thanks Srinivas Tamada!
ReplyDeleteIs the total voters supposed to be in percent? In teh demo it seems to be just teh total number.
Wow i LOVE THIS SITEE!!!!!!!!!!!!!!!!!!!!!!!!!!!!1
ReplyDeleteGreat Work
ReplyDeleteThanks shinivas for a good example of jquery functions..
ReplyDeleteAs some friends suggests that vote can be managed by IP to make it more accurate...
Thanks again.. Good work.
Good script... if we can allow only 1 vote per IP address, it would be great.
ReplyDeleteComplete Voting Tutorial with IP storing.
ReplyDeleteVoting system with jQuery, Ajax and PHP.
This is so cool tutorial, thanx for it? Can you add funcionality like on youtube, that buttons appear vhen you hover over a div, like on youtube coments? It vould be so great?
ReplyDeletehello Srinivas,
ReplyDeletei appreciate your work,
there is a problem when there is no record in database it give warning like
"Warning: Division by zero in "
because select query return 0 records
$result=mysql_query("select up,down from messages where id='$id'");
Solution:
1. you give database with one record.
2. if query return 0 record insert 1 record.
e.g:
//seleting up and down value from database
$result=mysql_query("select up,down from messages where id='$id'");
//checking the records
if(mysql_num_rows($result)>0){
mysql_query("update messages set $name=$name+1 where id='$id'");
}else{
mysql_query("insert into messages (up,down) values (1,1)");
}
i hope this will work also there should be database file in zip download for people help who don't know much about programming.
hope this will help.again i appreciate your work
Regards,
Mazhar ahmad
web developer
pakistan
this is not difficult anonymous you just have to add the below simple steps
ReplyDelete1.plece the rating div in another div.
2.apply style="display:none;" at rating div not on main div.
3. add this event mouseover and mouseout on main div.
i have write the code for you you can test this below.
onmousemove="document.getElementById('ratingdiv').style.display='block';"
onmouseout="document.getElementById('ratingdiv').style.display='none';">
thanks for the tutorial. Great work man but I have a question? How can I show the votebox or the content always and not only when the '.link' is clicked?
ReplyDeleteThank you.
Hi,
ReplyDeleteI run it, error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in E:\AppServ\www\tvs\youtube\rating.php on line 17
Warning: Division by zero in E:\AppServ\www\tvs\youtube\rating.php on line 22
Warning: Division by zero in E:\AppServ\www\tvs\youtube\rating.php on line 23
Ratings for this blog ( 0 total)
Thanks
How can I put the overview of the ratings to top of the page? I mean the z-index. Another element overlays the rating window =/
ReplyDeleteHi,
ReplyDeleteI run it, error:
Warning: Division by zero in C:\xampp\htdocs\youtube\rating.php on line 20
Warning: Division by zero in C:\xampp\htdocs\youtube\rating.php on line 21
Ratings for this blog ( 0 total)
Thanks
nice tutorial mate, well done
ReplyDeleteThank you..
ReplyDeletei gt dis problems when click the like/dislike
ReplyDeleteWarning: Division by zero in C:\wamp\www\youtube\rating.php on line 20
Warning: Division by zero in C:\wamp\www\youtube\rating.php on line 21
Ratings for this blog ( 0 total)
Hello! It's work! but I have one question!
ReplyDeleteHow can I do that rating was displayed already! do not click this?! I am sorry for my English I hope that you understand what I mean!
For people those want that viewers to vote 1 time a day
ReplyDelete1. Make a new table in mysql
CREATE TABLE IF NOT EXISTS `vote` (
`id` int(64) NOT NULL AUTO_INCREMENT,
`item_id` int(128) NOT NULL,
`ip` varchar(128) NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
2. Open rating.php replace this in the top
$id= $mysqli->real_escape_string($_POST['id']);
$name= $mysqli->real_escape_string($_POST['name']);
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("Y-m-d");
$exist_result = $mysqli->query("SELECT * FROM vote WHERE item_id = '$id' AND ip = '$ip' AND date = '$date'");
if (mysqli_num_rows($exist_result) == '0'){
$mysqli->query("UPDATE message SET $name=$name+1 WHERE id='$id'");
$mysqli->query("INSERT INTO vote (id, item_id, ip, date) VALUES (NULL, '$id', '$ip', '$date')");
}else{
}
I have never used mysql. Have everything in html but have no idea how to set up the database. http://www.brohaun.com/TEST/
ReplyDeleteAll i get is "oops something went wrong."
I set up the mysql with the information given, It is now connected with the database and I no longer get "oops something went wrong." However It does not seem to be recording anything. What could be causing this?
ReplyDeletelooks good
ReplyDeleteAnyone have a fix for this error?
ReplyDeleteWarning: Division by zero in /home/content/85/7370085/html/m/php/likedislike/likedislike_1.php on line 20
Warning: Division by zero in /home/content/85/7370085/html/m/php/likedislike/likedislike_1.php on line 21
Ratings for this blog ( 0 total)
Thanks!
I am looking to encapsulate this code into a clean javascript call that an external site would stick in to their site, and when someone clicks like it shows how many likes, it stored the results on the same site where the javascript resides. Is this possible with this script?
ReplyDeletehi would like to use this to my blog..how can i add it to my customized template..please help
ReplyDeletesecurity
ReplyDeleteid and ip
!$result < 0
That is not good solution for webiste with lot of traffic you could colapse the server.
ReplyDeleteYou need to make a table only for like/dislike (type: InnoDB)
This is really a nice little app...and ya , it's just an example app, if anyone want to use it on their website (with high or low traffic), they can modify it according to their requirements..well, thanks
ReplyDeleteHi,
ReplyDeleteI run it, error:
Warning: Division by zero in C:\xampp\htdocs\youtube\rating.php on line 20
Warning: Division by zero in C:\xampp\htdocs\youtube\rating.php on line 21
Ratings for this blog ( 0 total)
Thanks
I get
ReplyDeleteFatal error: Call to a member function real_escape_string() on a non-object in C:\xampp\htdocs\rating.php on line 7
with this code:
real_escape_string($_POST['id']);
$name= $mysqli->real_escape_string($_POST['name']);
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("Y-m-d");
$exist_result = $mysqli->query("SELECT * FROM vote WHERE item_id = '$id' AND ip = '$ip' AND date = '$date'");
if (mysqli_num_rows($exist_result) == '0'){
$mysqli->query("UPDATE streams SET $name=$name+1 WHERE id='$id'");
$mysqli->query("INSERT INTO vote (id, item_id, ip, date) VALUES (NULL, '$id', '$ip', '$date')");
}
else{
print("Sorry you have already voted!");
}
//$id=mysql_escape_String($_POST['id']);
//$name=mysql_escape_String($_POST['name']);
//
//mysql_query("UPDATE streams SET $name=$name+1 WHERE id='$id'");
$result=mysql_query("SELECT up, down FROM streams WHERE id='$id'");
$row=mysql_fetch_array($result);
$up_value=$row['up'];
$down_value=$row['down'];
$total=$up_value+$down_value;
$up_per=($up_value*100)/$total;
$down_per=($down_value*100)/$total;
?>
bump for an update on the IP script. I'm getting the error too
ReplyDeleteagree with rohan. nice apps. ill get this to my site
ReplyDeleteHi ,
ReplyDeleteI need some help from u ?
i developed a site which user gave comments and other users like or dislike that comments.
when any user click like or dislike anchor tags , count is updated in the database ; but not displaying the updated content on the web page.Only after refresh the web page it is showing count of the webpage.
could you help me how to refresh the comment part of the web page with-out refreshing the whole page.
thank U
How can i add username code to prevent double rating from same user?
ReplyDeleteHi, thansk for this awesome script. I'm trying to use the html code twice on same page but when i click on second code the srcipt result slidedown open on first one instead of second one ... is there anyway to call parent before to load content?
ReplyDeleteThanks in advance!
This is the example what i want to do with 2 ids but works on first one only:
ReplyDeletehttp://jsfiddle.net/Ke5AB/97/
How would you go about implementing this system on multiple pages? for example if there are pages of pictures that can be rated? Hope you can help, thanks
ReplyDelete$up_value=$row['up'];
ReplyDelete$down_value=$row['down'];
$total=$up_value+$down_value;
$up_per=($up_value*100)/$up_value;
$down_per=($down_value*100)/$down_value;
$up_value=$row['up'];
ReplyDelete$down_value=$row['down'];
$total=$up_value+$down_value;
$up_per=($up_value*100)/$up_value;
$down_per=($down_value*100)/$down_value;
can any body help me out, im getting an warning as:
ReplyDeleteWarning: Division by zero in rating.php on line 20
and
Warning: Division by zero in rating.php on line 21
waiting for ur early reply
Dude...Gud job yaar...!
ReplyDeleteDis code is not so effective..!!
A voter can like as many times he or she wants nd even like nd dislike at the same time....!!
Kindly review out dis code...!!
Hi,
ReplyDeleteAfter voting I receive "( ! ) Deprecated: mysql_escape_string(): This function is deprecated; use mysql_real_escape_string() instead. in up_vote.php on line 9"
this is great!
ReplyDeletebut unfortunately i need the same thing in asp.net! what should i do? I'm not using IIS in my project instead file system so i cant install any php packet also to embeded it in asp.net! please reply me soon! and thanx in advance!
that i'm looking for
ReplyDeletePLEASE ANYONE KNOWS WHY I GOT THIS ERROR???
ReplyDeleteWarning: Division by zero in C:\xampp\htdocs\hotelBookingSys\rating1.php on line 19
Warning: Division by zero in C:\xampp\htdocs\hotelBookingSys\rating1.php on line 20
Ratings for this website ( 0 total)