Log In

Email:
Password:
Keep me logged in

Forgot Password

Email:

wcet, w.c.e.t., designs, william, thomas



Archives
Categories
Sponsored Links


Like/Dislike Button
PHP Ajax jQuery JavaScript
Thursday, December 1, 2011 | Browse Category |

A 'thumbs up, thumbs down' system in which users can rate content. Code: Uses PHP to store the rating, Ajax to rate without refreshing the page, and jQuery/JavaScript for the Ajax callback function.







Related tutorial: Rate more than one piece of content on one page.
Related tutorial: Get the percentage of ratings that consist of just likes.
Related tutorial: Get the like percentage rate for more than one piece of content on one page.
MySQL:
Make a MySQL table for both the content and the ratings.
CREATE TABLE `content` (
   `id` INT NOT NULL ,
   `content` TEXT NOT NULL
) ENGINE = MYISAM ;
CREATE TABLE `ratings` (
   `rating` VARCHAR ( 7 ) NOT NULL ,
   `id` INT NOT NULL ,
   `ip` VARCHAR ( 50 ) NOT NULL
) ENGINE = MYISAM ;
INSERT INTO content VALUES ('1', 'Demo'), ('2', 'wcetdesigns.com');
PHP:
settings.php, file where all the important settings will be located and embedded in the last two files.
<?php

//CONNECTS TO YOUR DATABASE (MODIFY TO YOUR OWN SETTINGS)
$c mysql_connect("server""username""password");
$db mysql_select_db("your_database"$c);

//TABLES FOR THE CONTENT AND THE RATINGS (MODIFY IF TABLE NAMES ARE DIFFERENT)
$content 'content';
$ratings 'ratings';

$ip $_SERVER["REMOTE_ADDR"]; //IP ADDRESS

?>
headers.php, the file with the number of likes & dislikes, button image URLs, and whether the user has already rated.
<?php

//COUNT LIKES & DISLIKES
$q mysql_query("SELECT * FROM $ratings WHERE id='$id' AND rating='like'");
$likes mysql_num_rows($q);
$q mysql_query("SELECT * FROM $ratings WHERE id='$id' AND rating='dislike'");
$dislikes mysql_num_rows($q);

//LIKE & DISLIKE IMAGES
$l 'http://wcetdesigns.com/images/buttons/l_color.png';
$d 'http://wcetdesigns.com/images/buttons/d_color.png';

//CHECKS IF USER HAS ALREADY RATED CONTENT
$q mysql_query("SELECT * FROM $ratings WHERE id='$id' AND ip='$ip'");
$r mysql_fetch_assoc($q); //CHECKS IF USER HAS ALREADY RATED THIS ITEM

//IF SO, THE RATING WILL HAVE A SHADOW
if($r["rating"]=="like"){
    
$l 'http://wcetdesigns.com/images/buttons/l_color_shadow.png';
}
if(
$r["rating"]=="dislike"){
    
$d 'http://wcetdesigns.com/images/buttons/d_color_shadow.png';
}

//FORM & THE NUMBER OF LIKES & DISLIKES
$m '<img id="like" onClick="rate($(this).attr(\'id\'))" src="'.$l.'"> '.$likes.' &nbsp;&nbsp; <img id="dislike" onClick="rate($(this).attr(\'id\'))" src="'.$d.'"> '.$dislikes;
    
?>
jQuery/JavaScript:
view.php, the main file where the ratings will be displayed based on the content, which is referenced by the $id variable
<?php

//GOES TO ID 1 AUTOMATICALLY IF THERE'S NO ID IN THE URL
if(!$_GET["id"]){
    
header("Location: view.php?id=1");
} else {
    
$id $_GET["id"];
}

include(
"settings.php"); //INCLUDES THE IMPORTANT MySQL SETTINGS

$q mysql_query("SELECT * FROM $content WHERE id='$id'"); //GETS THE CONTENT ID
$r mysql_fetch_assoc($q);
$con $r["content"]; //CONTENT OF THE ID
$id $r["id"]; //NEW ID VARIABLE, USED TO CHECK IF IT'S IN THE DATABASE

?>

<script src="http://wcetdesigns.com/assets/javascript/jquery.js"></script>
<script>

function rate(rating){ //'rating' VARIABLE FROM THE FORM in view.php
   var data = 'rating='+rating+'&id=<?php echo $id; ?>';

   $.ajax({
     type: 'POST',
     url: 'rate.php', //POSTS FORM TO THIS FILE
     data: data,
     success: function(e){
       $("#ratings").html(e); //REPLACES THE TEXT OF view.php
     }
   });
}
</script>
<style>
/*GIVES THE POINTER TO THE BUTTONS ON MOUSEOVER*/
#like, #dislike {
   cursor: pointer;
}

</style>
<?php

//IF $id EXISTS, THEN COUNT LIKES & DISLIKES
if($id){
    include 
'headers.php'//FILE WITH THE NUMBER OF RATINGS, BUTTON IMAGE URLS, AND WHETHER USER HAS RATED
    
    //EVERYTHING HERE DISPLAYED IN HTML
    
echo $con.'<br><br><br><div id="ratings">'.$m.'</div>';
}
else
{
    echo 
"Invalid ID";
}

?>
Ajax:
rate.php, Ajax file where the rating process will take place.
<?php

$id 
$_POST["id"];
$rating $_POST["rating"];
$rating_type = array("like""dislike");

if(
in_array($rating$rating_type)){
    
    include(
"settings.php"); //INCLUDES THE IMPORTANT SETTINGS
    
    //CHECKS IF $id EXISTS
    
$q mysql_query("SELECT * FROM $content WHERE id='$id'");
    
$r mysql_fetch_assoc($q);
    
$id $r["id"]; //NEW ID VARIABLE, USED TO CHECK IF IT'S IN THE DATABASE
    
    //COUNTS LIKES & DISLIKES IF $id EXISTS
    
if($id)
    {
        
//CHECKS IF USER HAS ALREADY RATED CONTENT
        
$q mysql_query("SELECT * FROM $ratings WHERE id='$id' AND ip='$ip'");
        
$r mysql_fetch_assoc($q); //CHECKS IF USER HAS ALREADY RATED THIS ITEM
        
        //IF USER HAS ALREADY RATED
        
if($r["rating"]){
            if(
$r["rating"]==$rating){
                
mysql_query("DELETE FROM $ratings WHERE id='$id' AND ip='$ip'"); //DELETES RATING
            
} else {
                
mysql_query("UPDATE $ratings SET rating='$rating' WHERE id='$id' AND ip='$ip'"); //CHANGES RATING
            
}
        } else {
            
mysql_query("INSERT INTO $ratings VALUES('$rating', '$id', '$ip')"); //INSERTS INITIAL RATING
        
}
        
        include 
'headers.php'//FILE WITH THE NUMBER OF RATINGS, BUTTON IMAGE URLS, AND WHETHER USER HAS RATED
     
        //EVERYTHING HERE DISPLAYED IN HTML AND THE "ratings" ELEMENT FOR AJAX
        
echo $m;
    }
    else
    {
        echo 
"Invalid ID";
    }
}

?>

 2,280    1,261
53,498     6,266




(Optional)

(Optional in case you want a reply)



158 Comments
bharathi
its good


Saturday, July 19, 2014 at 12:53:56 AM
dron
Here is a like button widget ready to use http://likebtn.com/en/


Wednesday, July 9, 2014 at 2:09:47 AM
Jay
YOUR REG FILE FAILS! line 31 Fatal error: Call to undefined function randomString() in /home/content/45/8702745/html/assets/ajax/register/validate.php on line 31


Monday, June 16, 2014 at 9:30:07 AM
Jay
hi can i just string replace mysql to make them all mysqli and it all still work? if not can you redo this and update this to 2014 edition (version 2) for mysqli or prepered instead of the old mysql?


Monday, June 16, 2014 at 9:28:10 AM
adssdf
sdkjlflk dshfkldsj


Tuesday, April 29, 2014 at 11:17:53 AM
1 2 3 4 5 Next Last