A dynamic rating system is a common feature in modern web applications, enabling users to provide feedback by rating products, services, or content. This system can be implemented using jQuery, AJAX, PHP, and a database (such as MySQL) to store and retrieve ratings dynamically.
Table of Contents
- Introduction to Dynamic Rating Systems
- Setting Up the Project
- Creating the Database
- Building the HTML Structure
- Styling the Rating System with CSS
- Implementing jQuery for Rating Interaction
- Handling AJAX Requests for Real-Time Rating Submission
- Creating the Backend (PHP) to Store Ratings
- Fetching and Displaying Average Ratings Dynamically
- Enhancing the User Experience with Visual Effects
- Handling Edge Cases and Validations
- Testing the Rating System
- Optimizing Performance
- Conclusion
1. Introduction to Dynamic Rating Systems
A dynamic rating system allows users to rate products or services in real-time without reloading the page. A star-based rating system is the most common format. It provides a seamless and engaging user experience and helps businesses collect valuable feedback.
2. Setting Up the Project
Before we begin coding, we need to set up our project structure:
/rating-system
/css
style.css
/js
script.js
/php
save_rating.php
fetch_rating.php
index.html
database.sql
This structure will help organize the CSS, JavaScript, PHP, and HTML files efficiently.
3. Creating the Database
We will use MySQL to store user ratings. Open your database tool (e.g., phpMyAdmin) and create a database.
CREATE DATABASE rating_system;
USE rating_system;
CREATE TABLE ratings (
id INT AUTO_INCREMENT PRIMARY KEY,
item_id INT NOT NULL,
user_id INT NOT NULL,
rating INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Here, the ratings table stores:
item_id
– The item being rateduser_id
– The user who gave the ratingrating
– The actual rating (1 to 5 stars)created_at
– The timestamp of the rating
4. Building the HTML Structure
Create an index.html
file and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Rating System</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="rating-container">
<h2>Rate this Product</h2>
<div class="star-rating" data-item="1">
<span class="star" data-value="1">★</span>
<span class="star" data-value="2">★</span>
<span class="star" data-value="3">★</span>
<span class="star" data-value="4">★</span>
<span class="star" data-value="5">★</span>
</div>
<p id="rating-message"></p>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
5. Styling the Rating System with CSS
Create a style.css
file inside the css
folder:
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f4f4f4;
}
.rating-container {
background: white;
width: 300px;
padding: 20px;
margin: 100px auto;
box-shadow: 0px 0px 10px rgba(0,0,0,0.1);
border-radius: 8px;
}
.star-rating {
font-size: 30px;
color: #ccc;
cursor: pointer;
}
.star {
display: inline-block;
transition: color 0.3s;
}
.star:hover,
.star.active {
color: #f5a623;
}
6. Implementing jQuery for Rating Interaction
Create a script.js
file inside the js
folder:
$(document).ready(function () {
$(".star").hover(function () {
var value = $(this).data("value");
$(".star").each(function () {
if ($(this).data("value") <= value) {
$(this).addClass("active");
} else {
$(this).removeClass("active");
}
});
});
$(".star").click(function () {
var rating = $(this).data("value");
var itemId = $(".star-rating").data("item");
$.ajax({
url: "php/save_rating.php",
type: "POST",
data: { item_id: itemId, rating: rating },
success: function (response) {
$("#rating-message").html(response);
}
});
});
});
7. Handling AJAX Requests for Real-Time Rating Submission
Now, let’s create the backend file save_rating.php
:
<?php
$conn = new mysqli("localhost", "root", "", "rating_system");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$item_id = $_POST['item_id'];
$rating = $_POST['rating'];
$user_id = 1; // Static for now (Implement user authentication in real applications)
$stmt = $conn->prepare("INSERT INTO ratings (item_id, user_id, rating) VALUES (?, ?, ?)");
$stmt->bind_param("iii", $item_id, $user_id, $rating);
$stmt->execute();
echo "Thank you for rating!";
$stmt->close();
$conn->close();
?>
8. Fetching and Displaying Average Ratings Dynamically
To fetch and display average ratings, create fetch_rating.php
:
<?php
$conn = new mysqli("localhost", "root", "", "rating_system");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$item_id = $_GET['item_id'];
$sql = "SELECT AVG(rating) as avg_rating FROM ratings WHERE item_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $item_id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo round($row['avg_rating'], 1);
$stmt->close();
$conn->close();
?>
Modify script.js
to display the rating dynamically:
$(document).ready(function () {
var itemId = $(".star-rating").data("item");
function fetchRating() {
$.ajax({
url: "php/fetch_rating.php",
type: "GET",
data: { item_id: itemId },
success: function (avgRating) {
$("#rating-message").html("Average Rating: " + avgRating);
}
});
}
fetchRating();
});
9. Enhancing the User Experience
- Add animations using CSS
- Store the selected rating in local storage
- Disable rating after submission
10. Testing the Rating System
Test the rating system:
- Open the page
- Click on stars
- Refresh and check the stored rating
11. Optimizing Performance
- Use AJAX caching
- Optimize database queries
- Implement lazy loading
A dynamic rating system improves user interaction on websites. By using jQuery, AJAX, PHP, and MySQL, we created a real-time rating system that updates without refreshing the page.
Would you like to add user authentication or real-time rating updates?