Star rating system with jQuery, Ajax and PHP

In this tutorial you’ll learn how to build a rating system using jQuery, Ajax and PHP. With our simple script you can easily implement the dynamic 5 star rating system into your project.

We are going to create a jQuery rating system with PHP and MySQL. We had created rating.js file for handling all the jQuery works. Ajax is used for submitting the rating points to the PHP file (rating.php). rating.php file helps to insert or update the rating data into the MySQL database.


We have used the following files for dynamic 5 star rating system.

  • rating.js
  • rating.css
  • dbConfig.php
  • index.php
  • rating.php

Database Table Creation:

post_rating table is used to store the rating data. The post_rating table SQL are given below.

CREATE TABLE `post_rating` (
 `rating_id` int(11) NOT NULL AUTO_INCREMENT,
 `post_id` int(11) NOT NULL,
 `rating_number` int(11) NOT NULL,
 `total_points` int(11) NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1 = Block, 0 = Unblock',
 PRIMARY KEY (`rating_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

rating.js and rating.css Files:

rating.js file contains the all jquery codes required for rating system. rating.css is used for styling the rating stars. You can download these 2 files from below.

dbConfig.php File:

Database configuration and connection is done here.

//Database configuration
$dbHost 'localhost';
$dbUsername 'root';
$dbPassword '';
$dbName 'codexworld';

//Connect with the database
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);
'Connect error:'.$db->connect_error);

index.php File:

You will need to include the jQuery library, rating.js and rating.css.

<link href="rating.css" rel="stylesheet" type="text/css">
<script src=""></script>
<script type="text/javascript" src="rating.js"></script>

Attach codexworld_rating_widget when the document is loaded. codexworld_rating_widget() method is exists into the rating.js file. You can pass some options as key/value object to codexworld_rating_widget() method.

$(function() {
        starLength: '5',
        initialValue: '',
        callbackFunctionName: 'processRating',
        imageDirectory: 'images/',
        inputAttr: 'postID'

Available Options:
 starLength – How many star want to display. Default value: 5
 initialValue – Rating value when the document is loaded for first time. Default value: 0
 callbackFunctionName – Call the function, once the rating star is clicked. Default value:
 imageDirectory – Star image directory name. Default value: "images"
 inputAttr – Pass attribute value into the callback function. Default value:

Define the callback function processRating(). codexworld_rating_widget() method return the rated post ID and rating points into the callback function processRating(). Using Ajax we will send the post ID and rating points to the rating.php file.

function processRating(val, attrVal){
        type: 'POST',
        url: 'rating.php',
        data: 'postID='+attrVal+'&ratingPoints='+val,
        dataType: 'json',
        success : function(data) {
            if (data.status == 'ok') {
                alert('You have rated '+val+' to CodexWorld');
                alert('Some problem occured, please try again.');

When the page is loaded for first time, we will fetch the rating data from the database and display the overall rating.

include_once 'dbConfig.php';
//Fetch rating deatails from database
$query "SELECT rating_number, FORMAT((total_points / rating_number),1) as average_rating FROM post_rating WHERE post_id = 1 AND status = 1";
$result $db->query($query);
$ratingRow $result->fetch_assoc();

Into the HTML we only need an input field with ID and custom attributes for defining the post ID.

<input name="rating" value="0" id="rating_star" type="hidden" postID="1" />
<div class="overall-rating">
    (Average Rating <span id="avgrat"><?php echo $ratingRow['average_rating']; ?></span> Based on <span id="totalrat"><?php echo $ratingRow['rating_number']; ?></span>  rating)

rating.php File:

In this file we will get the post ID and rating points sent by AJAX. We will check if rating data is exists into the post_rating table based on a particular post ID. If exists, then the the number of rating and total points would be updated otherwise the new rating data would be inserted. At last fetch the number of rating and average points from the post_rating table by postID and return the rating data as a JSON format.

include_once 'dbConfig.php';
$postID $_POST['postID'];
$ratingNum 1;
$ratingPoints $_POST['ratingPoints'];
//Check the rating row with same post ID
$prevRatingQuery "SELECT * FROM post_rating WHERE post_id = ".$postID;
$prevRatingResult $db->query($prevRatingQuery);
$prevRatingResult->num_rows 0):
$prevRatingRow $prevRatingResult->fetch_assoc();
$ratingNum $prevRatingRow['rating_number'] + $ratingNum;
$ratingPoints $prevRatingRow['total_points'] + $ratingPoints;
//Update rating data into the database
$query "UPDATE post_rating SET rating_number = '".$ratingNum."', total_points = '".$ratingPoints."', modified = '".date("Y-m-d H:i:s")."' WHERE post_id = ".$postID;
$update $db->query($query);
//Insert rating data into the database
$query "INSERT INTO post_rating (post_id,rating_number,total_points,created,modified) VALUES(".$postID.",'".$ratingNum."','".$ratingPoints."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
$insert $db->query($query);
//Fetch rating deatails from database
$query2 "SELECT rating_number, FORMAT((total_points / rating_number),1) as average_rating FROM post_rating WHERE post_id = ".$postID." AND status = 1";
$result $db->query($query2);
$ratingRow $result->fetch_assoc();
$ratingRow['status'] = 'ok';
$ratingRow['status'] = 'err';
//Return json formatted rating data
echo json_encode($ratingRow);

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You


  1. Kevin Said...
  2. Zeehan Akhtar Mohammed Said...
  3. Kaustav Said...
  4. Heena Said...
  5. Greg Said...
  6. Hitesh Said...
  7. Hosean Mogammdi Said...
  8. Jason Said...
  9. David Said...
  10. Ganesh Babu Jonnadula Said...
  11. Kurt Said...
  12. Sara Said...
  13. Sara Said...
    • CodexWorld Said...
  14. Rintu Mohan Said...
  15. Murat Said...
  16. Vghe Said...
  17. Rookey Said...
  18. Rookey Said...
    • CodexWorld Said...
  19. Danny Said...
  20. Clm Said...
  21. Shimii Said...
  22. Landon Said...

Leave a reply