
Implementing a Content Rating System with jQuery
A content rating system allows users to provide feedback on articles, products, or other types of content by giving ratings, typically in the form of stars, thumbs-up/down, or numeric scores. Implementing such a system using jQuery ensures interactivity and responsiveness without requiring a full page reload.
In this guide, we’ll explore:
- What a content rating system is
- How to set up a rating system with jQuery
- Capturing user input and updating UI
- Sending data to the server using AJAX
- Storing ratings in a database
- Displaying average ratings dynamically
This tutorial will cover everything from basic UI design to backend integration, database storage, and security considerations.
1. Understanding a Content Rating System
A content rating system enables users to express their opinions about an item (e.g., a blog post, a product, a movie). The rating is typically stored in a database and used to compute an average score displayed to future visitors.
Common types of rating systems:
- Star Ratings (e.g., ⭐⭐⭐⭐⭐)
- Thumbs Up/Down (👍 👎)
- Numeric Scores (1-10)
For this tutorial, we’ll implement a 5-star rating system using jQuery and AJAX.
2. Setting Up the HTML Structure
We need a basic structure for the rating system. We’ll use HTML, CSS, and jQuery to create the front-end UI.
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Rating System</title>
    <link rel="stylesheet" href="styles.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="rating-container">
        <h2>Rate this Content</h2>
        <div class="star-rating">
            <span class="star" data-rating="1">★</span>
            <span class="star" data-rating="2">★</span>
            <span class="star" data-rating="3">★</span>
            <span class="star" data-rating="4">★</span>
            <span class="star" data-rating="5">★</span>
        </div>
        <p id="rating-message"></p>
    </div>
    <script src="script.js"></script>
</body>
</html>
- The star-rating div contains five stars (★) that users can click on.
- The data-rating attribute helps track the selected rating.
- A paragraph (#rating-message) is used to show feedback after selection.
3. Styling the Rating System
Now, let’s apply CSS to style the stars and make them interactive.
CSS Code (styles.css):
body {
    font-family: Arial, sans-serif;
    text-align: center;
    padding: 50px;
    background-color: #f4f4f4;
}
.rating-container {
    background: white;
    padding: 20px;
    width: 300px;
    margin: auto;
    border-radius: 10px;
    box-shadow: 0px 4px 6px rgba(0,0,0,0.1);
}
.star-rating {
    font-size: 30px;
    cursor: pointer;
    color: #ccc;
}
.star {
    display: inline-block;
    transition: color 0.3s;
}
.star:hover,
.star.active {
    color: #ffcc00;
}
#rating-message {
    margin-top: 10px;
    font-size: 16px;
    color: #333;
}
- Stars have a default gray color (#ccc).
- Hovering or clicking a star changes its color to yellow (#ffcc00).
- CSS transitions ensure a smooth effect when highlighting stars.
4. Adding jQuery for Interactivity
Now, we need jQuery to handle:
- Hover effects (temporary highlighting)
- Click events (saving the selected rating)
- Submitting the rating using AJAX
jQuery Code (script.js):
$(document).ready(function () {
    let selectedRating = 0;
    // Highlight stars on hover
    $('.star').hover(function () {
        let rating = $(this).data('rating');
        $('.star').each(function () {
            $(this).toggleClass('active', $(this).data('rating') <= rating);
        });
    });
    // Click event to select rating
    $('.star').click(function () {
        selectedRating = $(this).data('rating');
        $('#rating-message').text(`You rated this ${selectedRating} stars!`);
        
        // Send rating to server using AJAX
        $.ajax({
            url: 'submit_rating.php',
            type: 'POST',
            data: { rating: selectedRating },
            success: function (response) {
                console.log('Rating submitted:', response);
            },
            error: function () {
                alert('Error submitting rating.');
            }
        });
    });
});
- Hovering highlights the stars dynamically.
- Clicking selects a rating and sends it to the backend using AJAX.
- AJAX prevents page reload and ensures smooth user experience.
5. Backend: Storing Ratings in Database
To store and retrieve ratings, we need a simple PHP & MySQL backend.
Create Database Table
CREATE TABLE ratings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    rating INT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
PHP Script to Save Ratings (submit_rating.php)
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "rating_system";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
    die("Database connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $rating = intval($_POST["rating"]);
    
    $stmt = $conn->prepare("INSERT INTO ratings (rating) VALUES (?)");
    $stmt->bind_param("i", $rating);
    if ($stmt->execute()) {
        echo "Rating saved successfully!";
    } else {
        echo "Error saving rating.";
    }
    $stmt->close();
}
$conn->close();
?>
6. Displaying Average Ratings
To show an average rating, create a new PHP file:
get_average_rating.php
<?php
$conn = new mysqli("localhost", "root", "", "rating_system");
$result = $conn->query("SELECT AVG(rating) AS avg_rating FROM ratings");
$row = $result->fetch_assoc();
echo round($row['avg_rating'], 1);
$conn->close();
?>
Updating UI with jQuery
Modify script.js to fetch and display the average rating:
function loadAverageRating() {
    $.ajax({
        url: 'get_average_rating.php',
        type: 'GET',
        success: function (response) {
            $('#rating-message').text(`Average Rating: ${response} stars`);
        }
    });
}
$(document).ready(function () {
    loadAverageRating(); // Fetch average rating on page load
});
7. Security Considerations
- Use prepared statements to prevent SQL injection.
- Sanitize user input before storing it.
- Validate ratings (1-5) to prevent invalid data.
- Implement rate limiting to prevent spam.
By following this guide, you’ve successfully built a fully functional content rating system with jQuery, AJAX, PHP, and MySQL. Users can rate content, and ratings are stored in a database with the average displayed dynamically.
This approach can be expanded with features like:
✔️ User authentication (to allow one rating per user)
✔️ Enhanced UI with animations
✔️ Rating filters (most recent, highest rated)
Would you like help with adding any extra features?
