Like & Dislike System With jQuery, Ajax and PHP (Youtube Like Design)

Posted under :
Download the script Check the demo

If you are developing a blog, video share platform or a webzine, you would love to have a rating system when visitors can like or dislike the content of your page, here I introduce a “like/dislike” system with a simple stat widget little like the youtube design, take a look …

If you tryed the demo, things will be much easier so we start by creating a table called “wcd_yt_rate” , in the tuto i created under a database called “wcd_yt”

CREATE TABLE IF NOT EXISTS `wcd_yt_rate` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_item` int(11) NOT NULL,
`ip` varchar(25) NOT NULL,
`rate` int(1) NOT NULL,
`dt_rated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);

Here i will explain to you the php part, how we retreive the data and how we make the buttons works via ajax file

So first we have 2 buttons, one for like and the other for the dislike

<div class="like-btn">Like</div>
<div class="dislike-btn"></div>

Using jQuery, and on click on the button we change the look of the button by adding a class “.like-h” and we send the parameters we need to the ajax file (the example of code here is used for the like action)

In the parameters we send the action to do (like or dislike) and the pageID which is the unique id of the page or the content retreived from the content table in the data base (Setting it up is in the line 28 in the tuto)

$('.like-btn').click(function(){
$('.dislike-btn').removeClass('dislike-h');
$(this).addClass('like-h');
$.ajax({
type:"POST",
url:"ajax.php",
data:'act=like&amp;pageID='+pageID,
success: function(){
}
});
});

Now in the ajax.php file, we call the config.php file which we connect to the database with and then we check by IP if the user has already make a rate by counting the like and dislike of the pageID and his IP.

Then if the user have didnt rate yet , we add a new line in the table with his choice,
and if he already rated the content before, we make an update with his changes

include 'config.php';

extract($_POST);
$user_ip = $_SERVER['REMOTE_ADDR'];

$dislike_sql = mysql_query('SELECT COUNT(*) FROM wcd_yt_rate WHERE ip = "'.$user_ip.'" and id_item = "'.$pageID.'" and rate = 2 ');
$dislike_count = mysql_result($dislike_sql, 0);

$like_sql = mysql_query('SELECT COUNT(*) FROM wcd_yt_rate WHERE ip = "'.$user_ip.'" and id_item = "'.$pageID.'" and rate = 1 ');
$like_count = mysql_result($like_sql, 0);

if($act == 'like'): //if the user click on "like"
if(($like_count == 0) &amp;&amp; ($dislike_count == 0)){
mysql_query('INSERT INTO wcd_yt_rate (id_item, ip, rate )VALUES("'.$pageID.'", "'.$user_ip.'", "1")');
}
if($dislike_count == 1){
mysql_query('UPDATE wcd_yt_rate SET rate = 1 WHERE id_item = '.$pageID.' and ip ="'.$user_ip.'"');
}
endif;

if($act == 'dislike'): //if the user click on "like"
if(($like_count == 0) &amp;&amp; ($dislike_count == 0)){
mysql_query('INSERT INTO wcd_yt_rate (id_item, ip, rate )VALUES("'.$pageID.'", "'.$user_ip.'", "2")');
}
if($like_count == 1){
mysql_query('UPDATE wcd_yt_rate SET rate = 2 WHERE id_item = '.$pageID.' and ip ="'.$user_ip.'"');
}
endif;

The last thing you should know, id located in the index file and its how we retreive the count of the rates
So, for this, we count of how many like, dislike the content had from all the visitors with a “SELECT COUNT(*)”
to display it in the little widget.

You can setup the pageID by change the value of

$pageID = 'value to change';


  • ahmet

    wonderfull thank you

  • LordEVon

    I like it, but I have a question. How can this handle, if there is not yet rating?

    • ah in this case, we can think a little and we have 3 options: we can show that its 0 like – 0 dislike, and the width of the green and red bar will be at 0%, or we can add 1 like in the first rating, orrr we can show a message with “no rated yet” if nobody made a rate

      • LordEVon

        Thanks for your answer, I figured it out with an IF(). I call the function only if rate_like_count, rate_dislike_count are bigger then 0. So no error message, no problem. Thans

        • mukesh

          dgdfgfdg

          • ASDASFD

            deQDSD

  • thank you

  • Hello ! Very good script, but I have a “little” problem.
    When I used the script in a loop… the vote is appied for all articles of my loop … How can I do for fix that ?

    • Altavista

      You need add a ID in you class (id article for example)

      Before the click() binding you’re using is called a “direct” binding which will only attach the handler to elements that already exist. It won’t get bound to elements created in the future. To do that, you’ll have create a “delegated” binding by using on()

      • RedDragon

        $pageID = $_POST[‘id’]; // The ID of the page, the article or the video …
        it is not the way help!

  • trailninja

    Would it be better to use “1” and “-1” for rate instead of “1” and “2”, so you can get final rating value with just SELECT sum(rate) … ?

  • thank you

  • zegge

    how to vote 2 post????

  • Marco D’Elia

    Hi, I need an help,
    when the new line in mysql database is still not create I receive this error
    Warning: Division by zero in /web/htdocs/www.mysite.com/home/like.php on line 18
    this is the line:
    $count1 = $num_amount / $num_total;

    • Caleb

      Hey, you cannot divide by zeros at all! You must add a conditional that handles this.

    • mosravo

      Maro D’Elia replace the function with this to avoid seeing this error on your page, i guess this helps you, you can contact me on mosravo@yahoo.com for any question if you have any issues apart from this

      //function to calculate the percent
      function percent($num_amount, $num_total) {

      if($num_amount>0){

      $count1 = $num_amount / $num_total;
      $count2 = $count1 * 100;
      $count = number_format($count2, 0);
      return $count;
      }
      }

      • Marco D’Elia

        The project is working on http://www.segreti.it

        • RedDragon

          Hi You Edit $pageID change made How did you help added

  • Marco D’Elia

    I have a question?
    how can I see the change in the vote without refresh the page?

  • n a d i a

    Is there any way So I don’t have to use the ajax.php page?

  • Pingback: PHP Ajax Like System | Solutions for enthusiast and professional programmers()

  • Sujay

    How can I put this script on my blog http://bestindiaoffers.blogspot.in/

  • dorter

    You can also use http://likebtn.com which does not need any coding.

  • danger0ver

    not worked my site please help me

    Error code:

    Before the click() binding you’re using is called a “direct” binding
    which will only attach the handler to elements that already exist. It
    won’t get bound to elements created in the future. To do that, you’ll
    have create a “delegated” binding by using on() http://www.bitchfuck.net

  • Ghani Zac

    need to reload to get the new count ?? why ?

  • Admin

    works on blogger ?

  • Kenji

    Hi, the script is very nice and works perfectly, only one thing is when we click on “like” or “dislike” we have to refresh the page to see the result. Do you have any idea to add an automatic refresh like on youtube. Thanks so much

  • RedDragon

    $dislike_sql = mysql_query(‘SELECT COUNT(*) FROM wcd_yt_rate WHERE ip = “‘.$user_ip.'” and id_item = “‘.$pageID.'” and rate = 2 ‘); which parts will change help?

  • RedDragon

    Thank You Admin very well

  • Kenji

    Hi webcodo, it’s sad to see that no web coder seems to answer to any questions, is the website still updated?

Be notified for new scripts