Youtube like Rating with Jquery and Ajax
Wall Script
Follow Me:
Thursday, July 08, 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
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


51 comments:

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

    ReplyDelete
  2. 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!

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

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

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

    ReplyDelete
  6. Nice and Awesome as usually.
    Thanks.

    ReplyDelete
  7. Thanks Srinivas Tamada!

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

    ReplyDelete
  8. Wow i LOVE THIS SITEE!!!!!!!!!!!!!!!!!!!!!!!!!!!!1

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

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

    ReplyDelete
  11. 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?

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

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

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

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

    ReplyDelete
  16. 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 =/

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

    ReplyDelete
  18. nice tutorial mate, well done

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

    ReplyDelete
  20. 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!

    ReplyDelete
  21. 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{
    }

    ReplyDelete
  22. 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."

    ReplyDelete
  23. 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?

    ReplyDelete
  24. 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!

    ReplyDelete
  25. 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?

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

    ReplyDelete
  27. security

    id and ip

    !$result < 0

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

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

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

    ReplyDelete
  31. 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;
    ?>

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

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

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

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

    ReplyDelete
  36. 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!

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

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

    ReplyDelete
  38. 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
  39. $up_value=$row['up'];
    $down_value=$row['down'];
    $total=$up_value+$down_value;
    $up_per=($up_value*100)/$up_value;
    $down_per=($down_value*100)/$down_value;

    ReplyDelete
  40. $up_value=$row['up'];
    $down_value=$row['down'];
    $total=$up_value+$down_value;
    $up_per=($up_value*100)/$up_value;
    $down_per=($down_value*100)/$down_value;

    ReplyDelete
  41. can any body help me out, im getting an warning as:
    Warning: 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

    ReplyDelete
  42. Dude...Gud job yaar...!
    Dis 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...!!

    ReplyDelete
  43. Hi,

    After voting I receive "( ! ) Deprecated: mysql_escape_string(): This function is deprecated; use mysql_real_escape_string() instead. in up_vote.php on line 9"

    ReplyDelete
  44. this is great!
    but 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!

    ReplyDelete
  45. PLEASE ANYONE KNOWS WHY I GOT THIS ERROR???

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

    ReplyDelete

Make in India