9lessons programming blog
Loading Search
Thursday, July 8, 2010

Youtube like Rating with Jquery and Ajax

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

Youtube like rating

Download Script     Live Demo

Database Design
Messages Table :
CREATE TABLE messages(
id INT PRIMARY KEY AUTO_INCREMENT,
message TEXT,
up INT,
down INT);


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

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>';
}
?>

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

jQuery in Action, Second Edition
Sponsored Links

Share this post

Comments
{ 42 comments }
ValsiS said...

nice, very very nice, but you can put to vote only once by ip

Marius Patrascu said...

Oho, when I asked you if you could do this, I didn;t expect you'll make it so fast and so cool!

Thank you very much! It's just great!

robotismybot said...

needs lots of improvement. This wont work on heavy servers.

darkrishabh said...

hey 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

Diego E. said...

Nice, really nice, as usual

abdalla_programmer said...

very good post but I'm with "ValsiS" about voting by ip address.

Abdullah Al Mamun said...

Nice and Awesome as usually.
Thanks.

Anonymous said...

Thanks Srinivas Tamada!

Is the total voters supposed to be in percent? In teh demo it seems to be just teh total number.

Jonathan said...

Wow i LOVE THIS SITEE!!!!!!!!!!!!!!!!!!!!!!!!!!!!1

Anonymous said...

Great Work

Amit said...

Thanks shinivas for a good example of jquery functions..

As some friends suggests that vote can be managed by IP to make it more accurate...

Thanks again.. Good work.

Shashi said...

Good script... if we can allow only 1 vote per IP address, it would be great.

Srinivas Tamada said...

Complete Voting Tutorial with IP storing.

Voting system with jQuery, Ajax and PHP.

Anonymous said...

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?

admin said...

hello Srinivas,

i 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

admin said...

this is not difficult anonymous you just have to add the below simple steps

1.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';">

Anonymous said...

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?
Thank you.

Anonymous said...

Hi,

I 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

doenervich said...

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 =/

Anonymous said...

Hi,

I 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

Anonymous said...

nice tutorial mate, well done

Srinivas Tamada said...

Thank you..

Anonymous said...

i gt dis problems when click the like/dislike

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

Anonymous said...

Hello! It's work! but I have one question!
How 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!

Shu said...

For people those want that viewers to vote 1 time a day

1. 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{
}

Anonymous said...

I have never used mysql. Have everything in html but have no idea how to set up the database. http://www.brohaun.com/TEST/

All i get is "oops something went wrong."

Anonymous said...

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?

Anonymous said...

looks good

Anonymous said...

Anyone have a fix for this error?

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

Anonymous said...

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?

Anonymous said...

hi would like to use this to my blog..how can i add it to my customized template..please help

Anonymous said...

security

id and ip

!$result < 0

Anonymous said...

That is not good solution for webiste with lot of traffic you could colapse the server.
You need to make a table only for like/dislike (type: InnoDB)

Rohan Sehgal said...

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

Anonymous said...

Hi,

I 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

Anonymous said...

I get

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

Anonymous said...

bump for an update on the IP script. I'm getting the error too

hugh said...

agree with rohan. nice apps. ill get this to my site

raghavendra said...

Hi ,

I 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

DJ said...

How can i add username code to prevent double rating from same user?

Anonymous said...

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

Thanks in advance!

Anonymous said...

This is the example what i want to do with 2 ids but works on first one only:

http://jsfiddle.net/Ke5AB/97/

Post a Comment

Subscribe now!Recent Posts

Categories

Subscribe now!Popular Posts

People Says

@9lessons thank you for the great tutorials, we truly appreciate your contributions to the design community.

Smashing Magazine

Like Me

follow me
products

9lessons labs

9lessons clouds

Android application

Chrome Extension