jQuery Ratings Plugin with Database & Average Calculation

First you need to download and integrate a small and lightweight Javascript library in your project. The name of library is Starrr and you can download it from here. You may get the downloaded file in ZIP format so unzip it (of course). You will find a folder named “dist”, you will find 2 files, one is CSS and second will be of JS. You need to copy both these files and place them in your project folder. To setup the star ratings in your website, you need to include 3 CSS files and 2 JS files.

CSS

  1. Bootstrap
  2. Font Awesome
  3. Starrr

JS

  1. jQuery
  2. Starrr

So paste the following code at the top of file where you want to show ratings. We have used the CDN for Bootstrap, Font Awesome and jQuery for direct integration. But you can download them in your project and give relative path if you want. If you are already working on some project, then most probably you already have those CSS & JS files because they are used mostly in design part.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css">
<link rel="stylesheet" href="starrr.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="starrr.js"></script>

Database integration

You might already have a database with all the data and you just want to integrate this star ratings in it. So you might have an E-commerce site where you want to give ratings to products, or may have an online Job Portal where you want to give ratings to Clients or Freelancers etc. So for the sake of simplicity we are are creating simple products with just 2 fields, you might have a lot of other fields too but it will give you enough idea how to implement in your project. Create a new database in your phpMyAdmin named tutorials and run the following queries to create 1 table named products and other ratings where all ratings of each product will be stored:

--
-- Database: `tutorials`
--

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

--
-- Table structure for table `products`
--

CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `name` text NOT NULL
);

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `name`) VALUES
(1, 'Macintosh'),
(2, 'iMac'),
(3, 'iPod'),
(4, 'Apple II');

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

--
-- Table structure for table `ratings`
--

CREATE TABLE `ratings` (
  `id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `ratings` int(11) NOT NULL
);

Display all products

Now you need to display all products stored in your database. We are just displaying product name but surely you will be displaying other details too. Along with each product we will create a form to get product ID and show 5 stars from where user can give ratings and a submit button.

<?php
	// Connecting with database
	$conn = mysqli_connect("localhost", "root", "", "tutorials");

	// Getting all products
	$result = mysqli_query($conn, "SELECT * FROM products");

	// Displaying each product
	while ($row = mysqli_fetch_object($result)) {
?>

	<p>
		<?php
			echo $row->name;
		?>
	</p>

	<form method="POST" onsubmit="return saveRatings(this);">
		<input type="hidden" name="product_id" value="<?php echo $row->id; ?>">

		<div class="starrr"></div>

		<input type="submit">
	</form>

<?php
	}
?>

<script>
	$(function () {
		$(".starrr").starrr();
	});
</script>

Run the project now and you will be able to see all products stored in your database along with 5 stars to give ratings. Now you need to save ratings in ratings table when user click on submit button.

Save ratings

Our form creates a hidden input field where it is storing product ID, so now we first need to get the ratings and save those ratings in that particular product. You need to change the starrr() function to attach an change event that will be fired when user change his ratings and we will save that in a variable. Then we will attach an submit event in form and call an AJAX request and send the product ID and rating of user. Creates a new file named save-ratings.php that will store the ratings in database. You can also store user ID if you have login & registration system in your website, by getting the user ID from session or from cookies. So make the following changes in your above code and it will be able to save ratings in database:

index.php

var ratings = 0;
$(function () {
	$(".starrr").starrr().on("starrr:change", function (event, value) {
		ratings = value;
	});
});

function saveRatings(form) {
	var product_id = form.product_id.value;

	$.ajax({
		url: "save-ratings.php",
		method: "POST",
		data: {
			"product_id": product_id,
			"ratings": ratings
		},
		success: function (response) {
			// whatever server echo, that will be displayed here in alert
			alert(response);
		}
	});

	return false;
}

save-ratings.php

<?php

$product_id = $_POST["product_id"];
$ratings = $_POST["ratings"];

$conn = mysqli_connect("localhost", "root", "", "tutorials");

mysqli_query($conn, "INSERT INTO ratings (product_id, ratings) VALUES ('$product_id', '$ratings')");

// whatever you echo here, will be displayed in alert on user side
echo "Saved";

Go ahead and give ratings to some products and check your ratings table in your database, you will see your ratings along with product ID. This is where you can store user ID too from session or cookies if you are using login or sign up features.

Display average rating

We are already creating a loop to display all products, this is where we will get all ratings of each product and calculate it’s average and display as stars. So go ahead and paste the following code in your product’s while loop block:

while ($row = mysqli_fetch_object($result)) {

	// Getting ratings of current product using ID
	$result_ratings = mysqli_query($conn, "SELECT * FROM ratings WHERE product_id = '" . $row->id . "'");

	// Adding total ratings from each user
	$ratings = 0;
	while ($row_ratings = mysqli_fetch_object($result_ratings))
	{
		$ratings += $row_ratings->ratings;
	}

	// Calculating average from all ratings
	$average_ratings = 0;
	if ($ratings > 0)
	{
		$average_ratings = $ratings / mysqli_num_rows($result_ratings);
	}
?>

	<!-- This is where product stars will be displayed -->
	<!-- data-rating attribute will be used in Javascript below -->
	<div class="ratings" data-rating="<?php echo $average_ratings; ?>"></div>

	<!-- Product name and other fields -->

	<!-- Form goes here -->

<?php
	}
?>
	
<script>
	// Getting all div with ratings class
	var rating = document.getElementsByClassName("ratings");

	// Loop through all divs
	for (var a = 0; a < rating.length; a++)
	{

		// Display star on each div based on data-rating attribute value
		// readOnly will prevent the user changing it's value
		$(rating[a]).starrr({
			readOnly: true,
			rating: rating[a].getAttribute("data-rating")
		});
	}
<script>

That’s it, you have successfully added a star rating widget in your website. Everyone will be using this according to his project requirements and everyone will have different scenarios based on his needs. So if you have any problem, feel free to ask in the comments section below.

Leave a Reply

Please disable your adblocker or whitelist this site!