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.

star-rating-system-with-jquery-ajax-php-demo-by-codexworld

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.
 rating.js
 rating.css

dbConfig.php File:

Database configuration and connection is done here.

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

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

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="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></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() {
    $("#rating_star").codexworld_rating_widget({
        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){
    $.ajax({
        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');
                $('#avgrat').text(data.average_rating);
                $('#totalrat').text(data.rating_number);
            }else{
                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)
</div>

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.

<?php
include_once 'dbConfig.php';
if(!empty(
$_POST['ratingPoints'])){
    
$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);
    if(
$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);
    else:
        
//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);
    endif;
    
    
//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();
    
    if(
$ratingRow){
        
$ratingRow['status'] = 'ok';
    }else{
        
$ratingRow['status'] = 'err';
    }
    
    
//Return json formatted rating data
    
echo json_encode($ratingRow);
}
?>

14 Comments

  1. David Said...
  2. Ganesh Babu Jonnadula Said...
  3. Kurt Said...
  4. Sara Said...
  5. Sara Said...
    • CodexWorld Said...
  6. Rintu Mohan Said...
  7. Murat Said...
  8. Vghe Said...
  9. Rookey Said...
  10. Rookey Said...
    • CodexWorld Said...
  11. Clm Said...
  12. Landon Said...

Leave a reply

Connect With CodexWorld