Youtube like rating script jquery php

   In this Youtube like rating script jquery php tutorial we will create youtube like video rating script using jquery and php. Actually there is no use of php apart from saving the rating choice, (thats not less) but main role has been played by the jquery and css.

   Lets start with html, and dont forget to enable quirks mode, which will trigger strict mode in almost all browsers. This script now only supports firefox and google chrome. In all IE version its not working, I am not sure but i thing its PNG issue, there are few solution for fixing PNG issue, I dont want to waste time on it. I didnt tried to make it work in IE, I have left that on you :)

   I didnt implemented ip / user based rating so one user can either like it or dislike it. Here you can click like or dislike any number of times. You can make it so with few if else statements.

    This is how our script will look like

Youtube like rating script

Youtube rating script

Youtube rating script


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title> Youtube Thumbs Up Script </title>
  <meta name="author" content="">
  <meta name="keywords" content="">
  <meta name="description" content="">
  <script src="js/jquery-1.7.min.js"></script>
 </head>
 <body>
	<div class="container">
		<button id="button-container-like" class="option" value="1"><a class="thumbs-up"></a>Like</button>
		<button id="button-container-unlike" class="option" value="0"><a class="thumbs-down"></a></button>
		<div class="stats"></div>
		<input type="hidden" id="item" value="34">
	</div>  
 </body>
</html>

Lets style it with css

	.container{
		margin: 10% 30%;;
		padding:2px;
		font-family: verdana;
		font-size: 12px;
	}
	#button-container-like{
		background: -moz-linear-gradient(bottom, #dadada, #fff);
		background: -webkit-gradient(linear, center bottom, center top, from(#dadada), to(#fff)); 		
		border: 1px solid #CCCCCC;
		border-radius: 3px 0px 0px 3px;
		color: #000000;
		cursor: pointer;
		height:2.4em;
		width : 70px;
		font-family: verdana;
		font-size: 12px;
		line-height: 2em;
		float:left;
	}
	#button-container-unlike{
		background: -moz-linear-gradient(bottom, #dadada, #fff);
		background: -webkit-gradient(linear, center bottom, center top, from(#dadada), to(#fff)); 		
		border: 1px solid #CCCCCC;
		border-left: none;
		border-radius: 0px 3px 3px 0px;
		color: #000000;
		cursor: pointer;
		height: 2.4em;
		width : 35px;
		font-family: verdana;
		font-size: 12px;
		line-height: 2em;
		float:left;
	}
	.thumbs-up{
		background : url("images/icons.png") no-repeat scroll 2px -255px transparent;
		position: relative;
		height: 20px;
		display:block;
		width: 20px;
		clear: right;
		float: left;
	}
	.thumbs-down{
		background : url("images/icons.png") no-repeat scroll -63px -50px transparent;
		position: relative;
		height: 20px;
		display:block;
		width: 20px;
		clear: right;
		float: left;
		margin-right: 4px;
	}
	.tup-hover{
		background : url("images/icons.png") no-repeat scroll -37px -138px transparent;
	}
	.tdown-hover{
		background : url("images/icons.png") no-repeat scroll -36px -255px transparent;
	}
	.stats{
		border-radius: 5px;
		border : 1px solid #838383;
		display: block;
		clear:left;
		margin-top: 30px;
		display: none;
		height: auto;
		padding: 5px;
		width: 500px;
	}
	.stat-details .close{
		background : url("images/icons.png") no-repeat scroll 0px -132px transparent;
		float: right;
		height: 17px;
		width: 17px;
		margin:0px;
		padding:0px;
	}
	.stat-details table{
		font-size: 12px;
	}
	#small{
		font-size: 10px;
		color : #949494;
	}
	.bar{
		height:10px;
		display:inline-block;
	}
	.green{
		background: #64F141;
		border: 1px solid #148507;
	}
	.red{
		background: #FF4F4F;
		border: 1px solid #D50202;
	}
	.stat-option{
		display:block;
		line-height:20px;
		margin-top:5px;
		padding-top:3px;
	}
	.close{
		cursor: pointer;
	}

here’s the heart of script

	$("button").hover(
		function(){
			if($(this).val() == "1")   
				$(this).find(".thumbs-up").addClass("tup-hover");
			else
				$(this).find(".thumbs-down").addClass("tdown-hover");
		},
		function(){
			if($(this).val() == "1") {
				$(this).find(".thumbs-up").removeClass("tup-hover");
				$(this).find(".thumbs-up").addClass("thumbs-up");
			}else{
				$(this).find(".thumbs-down").removeClass("tdown-hover");
				$(this).find(".thumbs-down").addClass("thumbs-down");
			}	
		}
	);

	$(".close").live("click",function(){
		$(".stats").slideUp("fast");
	});

	$(".option").click(function(){
		 var option = $(this).val();
		 var item	= $("#item").val();
		 
		 $(".stats").slideDown("fast").html("Loading....");
		 $.ajax({
		   type: "POST",
		   url: "ajax_server.php",
		   data: "option="+option+"&item="+item,
		   success: function(responce){	
			    var json = jQuery.parseJSON(responce);
				var total = parseInt(json.likes) + parseInt(json.dislikes);
				
				option = (option == "1") ? "Liked" : "Disliked" ;
				var likes	 = (parseInt(json.likes) * 100 ) / total;
				var dislikes = (parseInt(json.dislikes) * 100 ) / total;

				$(".stats").html('<div class="stat-details"><span class="close"></span>You '+option+' this item. Thanks for the feedback !<br><br><b>Rating for this item</b> <span id="small"> ('+total+' total)</span><table border="0" width="100%"><tr><td width="25px"><span class="thumbs-up"></span></td><td width="50px;">'+json.likes+'</td><td><div class="bar green" style="width:'+likes+'%;"></div></td></tr><tr><td><span class="thumbs-down"></span></td><td>'+json.dislikes+'</td><td><div class="bar red" style="width:'+dislikes+'%;"></div></td></tr></table>');
		   }
		 });  
	});

ajax_server.php to store and fetch record

<?php
include("config.php");

if(isset($_POST)){
	extract($_POST);
	
	//check if item liked or disliked ??
	($option) ? $like = 1 : $dislike = 1;

	// what to update ?
	($like) ? $action = "likes" : $action = "dislikes";

	// check if entry allready exists ??
	$exist = mysql_num_rows(mysql_query("select * from ".$dbtable." where `item-id` =".$item));
	
	if(!$exist){
		mysql_query("insert into ".$dbtable." values('','".$item."','".$like."','".$dislike."')");
	}else{
		mysql_query("update ".$dbtable." set ".$action." = ".$action." +1 where `item-id` = ".$item);
	}

	// get review count
	$count = mysql_fetch_assoc(mysql_query("select * from ".$dbtable." where `item-id` = ".$item));
	echo json_encode($count);
} 
?>

Simple database table structure

CREATE TABLE IF NOT EXISTS `likes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `item-id` int(11) NOT NULL,
  `likes` int(11) NOT NULL,
  `dislikes` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

View Demo  Download

View Demo (Rate Once)  Download (Rate Once)

 

About Amit

   Myself Amit Patil from Maharashtra (India). I have been working as a Web Application Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically i am a PHP developer but now a days exploring more in CSS and javascript.

Comments

  1. Nice example of a youtube rating script.

  2. Can this script can be redesigned for unique ip addresses? Because from single IP addresss i am able to do multiple likes are dislikes

    • Rajandran, I am little bz now a days so cant make this changes right now…but there will be next version with this feature for sure, may be in this week on;y.

    • mahorpriyanka4@gmail.com' Priyanka says:

      hi amit
      i want php script for comment like youtub…plz help me..

      • Yes, I can make that comment script, but if its urgent one then it wont be possible, its hard for me to find some free time.

  3. I have added IP based version, So users can rate the item only once.

  4. Does it still works with the new YouTube’s interface?
    And how to install it with Greasemonkey/Tampermonkey?
    I’m deeply apologize if this kind of question is not allowed or you already guided how, but I can’t find it anywhere.

    • @Acellutor : This is not greasemonkey script…its standalone script that u can use as it is in your application.

  5. Hi, It doesn’t seem to work? I have created a new table etc but when i click on thumbs up, it says Loading…. and that’s it. Any ideas?

    • you need to set database login credentials, open config.php and change db_login and db_pass values. It should work.

  6. Hi Amit,
    thanks a lot for the distribution of your work!! I got same problem as andy – loading… thats it. the connection to the table is set though as my database updates whenever I rate. Do you have anything in mind by chance?

  7. Amit, great script, I noticed on the ip version there is a hidden field for an id. All well and good for what I am trying to use this for. BUT my issue is with having this on the same page. If there is examples: 1, 2, and 3. And I click on like on example 1, the 2 and 3 boxes show up as well. Is there a way to make it so each one is distinct and still work? Please do let me know as I am trying to integrate this into a project today.
    Thanks so much!

  8. Hey Amit Sir,
    I am 12 yrs old kid and i love your script. these are really cool. Can make facebook like chat bar? :)

  9. Hi Amit,
    I was wondering if this awesome script can be inserted into a plugin for joomla 2.5?
    Thanks.

    Regards.

    • It can be converted in anything….because there are no third party contents apart from javascript, css, & html.

  10. Hey Amit!

    I’ve been searching for something exactly like this for WordPress (Like/Dislike, limited by unique IP). And here it is, but it’s not for WordPress, though. I was just wondering if you could help me convert this into a plugin where this would be added below each post.

    I could try to do it myself, but I’m not confident enough that I could accurately convert your MySQL comments into WordPress’s $wpdb ones (http://codex.wordpress.org/Class_Reference/wpdb), nor am I entirely sure where to put the contents of ajax_server.php (in functions.php in theme or place the file in the theme root by itself?). I guess the like button could then be appended after the_content (after each post) like this: http://pastebin.com/LQ0VRy0x

    Is this script fine for security, especially if it was used with WordPress. I don’t want to get hacked using it.

    Your help would be immensely appreciated!

    Thanks,
    Mike

    • I am sorry to say but i am not in to wordpress plugin development, otherwise u would have seen lot of wp plugin on my blog :P
      I cant suggest u where the files and plugins should be :(

  11. How to integrate Youtube like rating on php-fusion?

  12. Amit, thanks for all your help. My issue is with having two on the same page too. Could you email me the updated code? And can I integrate my users?

  13. hi there Amit, nice script, I have the sam problem with “Loading…” i don’t know how to solve it…
    I don’t know gow config.php works…

  14. mahorpriyanka4@gmail.com' Priyanka says:

    tell me table structure………….

  15. hello Amit. I want the code for multiple item liking. I saw that you sent a script for this problem to other user that posted the question ” If there is examples: 1, 2, and 3. And I click on like on example 1, the 2 and 3 boxes show up as well. Is there a way to make it so each one is distinct and still work?”.
    I want this the script too.
    Thanks a lot.

  16. Hi Amit,

    I have modified your value from “34″ to <input type="hidden" id="item" value="”>
    I am storing a alpha numeric value in item-id using which is related to each video
    the sql insert is working fine as i click like and dislike, but the ajax to display is total likes and dislikes is stuck at loading

    can you please help?
    Abi

  17. I need script,whichlike the video on Vube ?
    Can you help me?

    • Its not possible, though programming we cant like a video, it needs valid user account to like a video.

  18. that’s what i am looking for

  19. cool script , easy to install and to use i was waiting for the (Rate Once) version and its really cool :)
    BUT :
    after liking or disliking it shows warning msg says You have already rated this item !
    and the rating bars and percentage disappear :| LOL
    suppose i want to see where the rating reached ( rating results like/dislike ) what do i do ? change my ip and delete cookies ? LOL
    am i missing something here ?

    • If you want to see the rating, you need to fetch it from the database, voting count has been stored in the database to display wherever you want.

  20. Hi Amit,

    Thank you for your great script. I have copied every thing and also created the db but its not working. It is saying undifined for both like and dislike and doesn’t count votes at all. I would appreciate if you could help me.

    Thank you

  21. Hi,
    Sorry for the mistakes, I’m French.
    Thank you for this script. I solved the multiple item but I do not have the message “You have already voted”

    Thank you

  22. My script has 40 different records from one database, is it possible to create 40 different like/dislike records too which work seperatly from each other?

  23. You Script is great i was looking for something like that. i have integrated your script as a e107 CMS plugin. I realy appriciate your work and looking forward for any new stuff you will write. Good job and Thanks.

  24. Hi
    I am running your script on xammp localhost with hostname=”localhost” username=”root”, pass=” ” and database=”ytube” but not working. On clicking any of two buttons shows loading…. Please help me.

Speak Your Mind

*


*

Notify me of followup comments via e-mail. You can also subscribe without commenting.

More in Ajax, CSS, jQuery, PHP (19 of 41 articles)


    I always wanted to be a Iphone developer but because of lack of resources like MAC machine and time i ...