Facebook Like Emoji Rating with PHP using jQuery AJAX

by Vincy. Last modified on July 19th, 2022.

Facebook like emoji rating is one of my favorite feature which can be a very useful gimmick for a web page for sure. It is especially for collecting the user’s emotion when they add rating or likes. In this tutorial, I am going to simulate this feature with a PHP example using jQuery AJAX.

In this example, a list of records is displayed from the database. Each record contains an option to the user to add likes. On hovering the “like” option shown on the example page, the emoji icons will be pop over to add the likes by sharing emotions.

In a previous tutorial, we have seen how to add a 5-star rating feature using PHP. This emoji rating example code will be more or less same as 5-star rating code. If you read and familiarise the simple star rating code then this example will be very easy for you. If you are searching for the example code for implementing star rating with JavaScript, then the linked article will be helpful.

Emoji Rating with PHP using jQuery AJAX

The add or update user likes are done via AJAX to provide a smooth and trendy feel to the user while sharing their emotions and likes. By clicking the emoji icons, the emotion data and the row ident will be sent to the PHP code via AJAX to update the database.

The likes count and the unique emotions are collected from the database and displayed on each row. After performing the AJAX add/update action, the UI will be updated with the latest emoji rating without page refresh.

HTML Page to Display Dynamic Results with Emoji Rating Option

In this example, I have used tbl_tutorial data to be displayed dynamically on the landing page. This table contains 3 records with the tutorial name and description on each. For each row, a like option will be displayed.

On hovering the like option, the emoji icons will be displayed. By clicking a particular emoji icon, the corresponding emotion data will be posted to the PHP via AJAX. Previously, we have learned how to create a PHP comments system to post text comments with emojis.

In this example, the user interface will have the stored emotion data for each record on page load. And, this data will be updated via AJAX on each like action performed by the user.

index.php

<?php
// Here the member id is harcoded.
// You can integrate your authentication code here to get the logged in member id
$member_id = 7;
$emojiArray = array(
    "like",
    "love",
    "smile",
    "wow",
    "sad",
    "angry"
);
require_once __DIR__ . '/lib/Rate.php';
$rate = new Rate();
$result = $rate->getAllPost();
?>
<HTML>
<HEAD>
<TITLE>Facebook Like Emoji Rating with PHP using jQuery AJAX</TITLE>
<link href="assets/css/style.css" rel="stylesheet" type="text/css" />
<script src="vendor/jquery-3.2.1.min.js" type="text/javascript"></script>
</HEAD>
<BODY>
	<h2>Facebook Like Emoji Rating with PHP using jQuery AJAX</h2>
	<table class="demo-table">
		<tbody>
<?php
if (! empty($result)) {
    $i = 0;
    foreach ($result as $tutorial) {
        $ratingResult = $rate->getRatingByTutorialForMember($tutorial["id"], $member_id);
        $ratingVal = "";
        if (! empty($ratingResult[0]["rating"])) {
            $ratingVal = $ratingResult[0]["rating"];
        }
        ?>
        <tr>
				<td valign="top">
					<div class="feed_title"><?php echo $tutorial["title"]; ?></div>
					<div><?php echo $tutorial["description"]; ?></div>
					<div id="tutorial-<?php echo $tutorial["id"]; ?>"
						class="emoji-rating-box">
						<input type="hidden" name="rating" id="rating"
							value="<?php echo $ratingVal; ?>" />

						<div class="emoji-section">
							<a class="like-link" onmouseover="showEmojiPanel(this)"
								onmouseout="hideEmojiPanel(this)"><img src="like.png" /> Like</a>
							<ul class="emoji-icon-container">
                        <?php
        foreach ($emojiArray as $icon) {
            ?>
                            <li><img
									src="icons/<?php echo $icon; ?>.png" class="emoji-icon"
									data-emoji-rating="<?php echo $icon; ?>"
									onClick="addUpdateRating(this, <?php echo $tutorial["id"]; ?>)" /></li>
                        <?php
        }
        ?>
                        </ul>
						</div>
						<div id="emoji-rating-count-<?php echo $tutorial["id"]; ?>"
							class="emoji-rating-count">
                            <?php
        if (! empty($tutorial["rating_count"])) {
            echo $tutorial["rating_count"] . " Likes";
            ?>
                            <?php
            if (! empty($tutorial["emoji_rating"])) {
                $emojiRatingArray = explode(",", $tutorial["emoji_rating"]);
                foreach ($emojiRatingArray as $emojiData) {
                    ?>
                                    <img
								src="icons/<?php echo $emojiData; ?>.png" class="emoji-data" />
                                <?php
                }
            }
        } else {
            ?>
                            No Ratings
                           <?php  } ?>
                    </div>
					</div>
				</td>
			</tr>
<?php
    }
}
?>
</tbody>
	</table>
</BODY>
</HTML>

Display Emojis and Add Update Rating using jQuery AJAX

This script shows the jQuery functions created for show/hide emoji icons on the mouse movement with respect to the “like” element in the UI. Also, it contains the function to perform the add/update emoji rating via AJAX.

The showEmojiPanel and hideEmojiPanel functions are called on the mouse-over and mouse-out event of the “like” text link which exists on each row. These functions invoke the jQuery show hide to toggle the emoji icon container element. On clicking the emoji icons, the addUpdateRating() function is called. In this function, the AJAX request will be sent to the PHP.

The AJAX method calls the addUpdateRating.php by posting row ident and emotion data as the parameters. After successful AJAX flow, the success callback will receive the response from the server-side to update the UI. In this example, it receives the Likes Count and Distinct emoji icons in HTML format.

index.php (JavaScript in landing page HTML)

function showEmojiPanel(obj) {
	$(".emoji-icon-container").hide();
	$(obj).next(".emoji-icon-container").show();
}
function hideEmojiPanel(obj) {
	setTimeout(function() {
		$(obj).next(".emoji-icon-container").hide();
	}, 2000);
}

function addUpdateRating(obj, id) {
	$(obj).closest(".emoji-icon-container").hide();
	$.ajax({
		url: "lib/addUpdateRating.php",
		data: 'id=' + id + '&rating=' + $(obj).data("emoji-rating"),
		type: "POST",
		success: function(data) {
			$("#emoji-rating-count-" + id).html(data);
		}
	});
}

PHP Code to Process Emoji Rating Request

In this PHP code, the AJAX request is received with the posted parameters tutorial_id and emoji_rating. In includes the PHP Rate.php class to invoke the function to read and update the rating database.

In this code, getRatingByTutorialForMember function read the database result to check if the user already added the likes for the tutorial. If not, a new record will be added to the tbl_member_rating table by invoking the addRating function. If there is already an entry on the rating database, then the member rating will be updated.

After performing the add or update the rating count and emotion data are formed in a HTML format. This HTML data will be sent to the response of the AJAX request to update the UI.

lib/addUpdateRating.php

<?php
// Here the member id is harcoded.
// You can integrate your authentication code here to get the logged in member id
$member_id = 7;
if (! empty($_POST["rating"]) && ! empty($_POST["id"])) {
    require_once __DIR__ . '/Rate.php';
    $rate = new Rate();

    $ratingResult = $rate->getRatingByTutorialForMember($_POST["id"], $member_id);
    if (! empty($ratingResult)) {
        $rate->updateRating($_POST["rating"], $ratingResult[0]["id"]);
    } else {
        $rate->addRating($_POST["id"], $_POST["rating"], $member_id);
    }

    $postRating = $rate->getRatingByTutorial($_POST["id"]);

    if (! empty($postRating[0]["rating_count"])) {
        echo $postRating[0]["rating_count"] . " Likes";
        if (! empty($postRating[0]["emoji_rating"])) {
            $emojiRatingArray = explode(",", $postRating[0]["emoji_rating"]);
            foreach ($emojiRatingArray as $emojiData) {
                ?>
<img src="icons/<?php echo $emojiData; ?>.png" class="emoji-data" />
<?php
            }
        }
    }
}
?>

PHP Classes to Access and Update Database

In this example, I have created two PHP classes for accessing and performing database insert or update on the rating table. The Rate.php class contains functions to create the database query and form query param types and value array. The DBController.php class will take care of establishing the connection and prepare required query statements to perform database related operations.

This file contains functions to get all the records from the database with rating data. The getAllPosts function uses a left join query to get the tutorial and its rating data. The group_concat function is used to get the collective, distinct emotion data from the database.

It also contains the functions to get the tutorial database by member id and to get the rating data by tutorial id. The addRating and updateDating functions form the posted rating data and type in an array format. This array will be used to bind the param array with the query statement on DBController class.

lib/Rate.php

<?php
use Phppot\DataSource;

require_once __DIR__ . '/DataSource.php';

class Rate extends DataSource
{

    function getAllPost()
    {
        $sql = "SELECT tutorial.*, COUNT(tbl_member_rating.rating) as rating_count, group_concat(distinct rating) as emoji_rating   FROM tutorial LEFT JOIN tbl_member_rating ON tutorial.id = tbl_member_rating.tutorial_id GROUP BY tutorial.id";

        $postResult = $this->select($sql);
        return $postResult;
    }

    function getRatingByTutorial($tutorial_id)
    {
        $sql = "SELECT tutorial.*, COUNT(tbl_member_rating.rating) as rating_count, group_concat(distinct rating) as emoji_rating FROM tutorial LEFT JOIN tbl_member_rating ON tutorial.id = tbl_member_rating.tutorial_id WHERE tbl_member_rating.tutorial_id = ? GROUP BY tbl_member_rating.tutorial_id";
        $paramType = 'i';
        $paramValue = array(

            $tutorial_id
        );

        $postResult = $this->select($sql, $paramType, $paramValue);
        return $postResult;
    }

    function getRatingByTutorialForMember($tutorial_id, $member_id)
    {
        $sql = "SELECT * FROM tbl_member_rating WHERE tutorial_id = ? AND member_id = ?";
        $paramType = 'ii';
        $paramValue = array(
            $tutorial_id,
            $member_id
        );

        $ratingResult = $this->select($sql, $paramType, $paramValue);

        return $ratingResult;
    }

    function addRating($tutorial_id, $rating, $member_id)
    {
        $sql = "INSERT INTO tbl_member_rating (tutorial_id,rating,member_id) VALUES (?, ?, ?)";
        $paramType = 'isi';
        $paramValue = array(
            $tutorial_id,
            $rating,
            $member_id
        );
        $this->insert($sql, $paramType, $paramValue);
    }

    function updateRating($rating, $rating_id)
    {
        $sql = "UPDATE tbl_member_rating SET  rating = ? WHERE id= ?";
        $paramType = 'si';
        $paramValue = array(
            $rating,
            $rating_id
        );
        $this->execute($sql, $paramType, $paramValue);
    }
}
?>

Database Script

Below SQL script is used to run this example in your PHP environment. Import this script by using database client like PHPMyAdmin, SQLYog and anything else.

--
-- Table structure for table `tbl_member_rating`
--

CREATE TABLE `tbl_member_rating` (
  `id` int(11) NOT NULL,
  `tutorial_id` int(11) NOT NULL,
  `member_id` int(11) NOT NULL,
  `rating` varchar(25) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_member_rating`
--

INSERT INTO `tbl_member_rating` (`id`, `tutorial_id`, `member_id`, `rating`) VALUES
(12, 1, 6, 'smile'),
(13, 2, 6, 'love'),
(14, 3, 6, 'love'),
(15, 1, 7, 'wow'),
(16, 2, 7, 'smile'),
(17, 3, 7, 'like');

-- --------------------------------------------------------

--
-- Table structure for table `tutorial`
--

CREATE TABLE `tutorial` (
  `id` int(8) NOT NULL,
  `title` varchar(255) CHARACTER SET utf8 NOT NULL,
  `description` text CHARACTER SET utf8 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tutorial`
--

INSERT INTO `tutorial` (`id`, `title`, `description`) VALUES
(1, 'Favorite Star Rating with jQuery', '\0This tutorial is for doing favorite star rating using jQuery. It displays list of HTML stars by using li tags. These stars are highlighted by using CSS and jQuery based on the favorite rating selected by the user.'),
(2, 'PHP RSS Feed Read and List', '\0PHP\'s simplexml_load_file() function is used for reading data from xml file. Using this function, we can parse RSS feed to get item object array.'),
(3, 'jQuery AJAX Autocomplete Country Example', 'Autocomplete feature is used to provide auto suggestion for users while entering input. It suggests country names for the users based on the keyword they entered into the input field by using jQuery AJAX.');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_member_rating`
--
ALTER TABLE `tbl_member_rating`
  ADD PRIMARY KEY (`id`),
  ADD KEY `tut_rate_id` (`tutorial_id`);

--
-- Indexes for table `tutorial`
--
ALTER TABLE `tutorial`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_member_rating`
--
ALTER TABLE `tbl_member_rating`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18;

--
-- AUTO_INCREMENT for table `tutorial`
--
ALTER TABLE `tutorial`
  MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
COMMIT;

Facebook Like Emoji Rating Output

The following screenshot shows the output of ths example simulating the Facebook like emoji rating.

Facebook Like Emoji Rating Output

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “Facebook Like Emoji Rating with PHP using jQuery AJAX”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page