Star Rating System Using PHP and Jquery with ajax – onlinecode

Star Rating System Using PHP and Jquery with ajax – onlinecode

In this post we will give you information about Star Rating System Using PHP and Jquery with ajax – onlinecode. Hear we will give you detail about Star Rating System Using PHP and Jquery with ajax – onlinecodeAnd how to use it also give you demo for it if it is necessary.

In this article, we are going to create add a star rating in php. here We have considered a t-shirt as a product. When a customer buys a product that time adds the rating and comment to a product. so we will discuss about a 5 star rating system in php mysql.

Step1: Create the database and table.

Now, first, we create a database and create an item_rating table.

PHP
CREATE TABLE 'item_rating' (
  'id' int(255) NOT NULL,
  'rate_number' varchar(255) NOT NULL,
  'title' varchar(255) NOT NULL,
  'comment' text NOT NULL,
  'created' datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step2: create the index.php file.

Second, we will the configuration of the database. after then we will create a rating system using the bootstrap. when we will select star on the click on the star. we will use ajax call to pass data after selecting a star, title, and comment. we will get rating data using the count_rate_data function.

PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "rating";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

$sql="SELECT SUM(rate_number) AS total_rate,count(id) as number_record FROM item_rating";
$result = mysqli_query($conn, $sql);
$data = mysqli_fetch_array($result);

function count_rate_data($rate_number)
{
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "rating";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    $sql="SELECT count(id) as number_record FROM item_rating where rate_number='".$rate_number."' ";
    $result = mysqli_query($conn, $sql);
    $data = mysqli_fetch_array($result);
    if(!empty($data['number_record']))
    {
        return $data['number_record'];
    }
    else{
        return '0';
    }

}
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
  <!-- Font Awesome Icon Library -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
* {  box-sizing: border-box;} body {  font-family: Arial;  margin: 0 auto;   max-width: 800px;  padding: 20px; }
.heading {  font-size: 25px;  margin-right: 25px; } .fa {  font-size: 25px; } .checked {  color: orange; }
.side {  float: left;  width: 15%;  margin-top:10px; } .middle {  margin-top:10px;  float: left;  width: 70%; }
.right {  text-align: right; } .row:after {  content: "";  display: table;  clear: both; }
.bar-container {  width: 100%;  background-color: #f1f1f1;  text-align: center;  color: white; }
.bar-5 {width: <?php echo (count_rate_data('5')*100)/$data['number_record'];  ?>%; height: 18px; background-color: #4CAF50;} .bar-4 {width: <?php echo (count_rate_data('4')*100)/$data['number_record'];  ?>%; height: 18px; background-color: #2196F3;} .bar-3 {width: <?php echo (count_rate_data('3')*100)/$data['number_record'];  ?>%; height: 18px; background-color: #00bcd4;}
.bar-2 {width: <?php echo (count_rate_data('2')*100)/$data['number_record'];  ?>%; height: 18px; background-color: #ff9800;} .bar-1 {width: <?php echo (count_rate_data('1')*100)/$data['number_record'];  ?>%; height: 18px; background-color: #f44336;}
label.error{ color:red; } .well{ margin-top: 25px; } .rating_bar{ margin-top: 20px; } .view_rating{ border-bottom: 1px solid #e3e3e3; padding: 20px; } .view_rating:last-child { border: none; }
@media (max-width: 400px) {  .side, .middle {    width: 100%;  }  .right {    display: none;  }}
</style>
<script>
$(document).ready(function(){
    $('.rating .fa-star').click(function(){
        if($(this).hasClass('checked')) {
            $(this).toggleClass('checked');
            $(this).prevAll('.fa-star').addClass('checked');
            $(this).nextAll('.fa-star').removeClass('checked');
        }
        else
        {
            $(this).toggleClass('checked');
            $(this).prevAll('.fa-star').addClass('checked');
        }
        $("#hdnRateNumber").val($('.checked').length);
    });
    $("#frmRating").validate({
        rules: {
            txtTitle: {
                required: true
            },
            txtComment: {
                required: true
            }
        },
        submitHandler: function (form) {
            //Your code for AJAX starts
            jQuery.ajax({
                url: 'saveData.php',
                type: "post",
                data: $(form).serialize(),
                success: function (data) {
                    if(data=="success")
                    {
                        window.location.reload();
                    }
                },
                error: function () {
                }
            });
        }
    });
});
</script>
</head>
<body>

<div >
    <div ><img src="t-shirt.jpg" width="175"></div>
    <div >
        <b>Men Maroon Printed Round Neck T-shirt</b></p>
        PRODUCT DETAILS</p>
        Rust solid T-shirt, has a round neck, long sleeves</p>
        Material & Care</p>
        Cotton</p>
        Machine-wash</p>
    </div>
</div>
<div >
    <div >
        <div >
            <div >
                 <span ><?php echo $data['total_rate']/$data['number_record'];?></span> average based on <?php echo $data['number_record']; ?> reviews.</p>
            </div>
            <div >
                <button type="button"  data-toggle="modal" data-target="#myModal">Rate Product</button>
            </div>
        </div>
        <hr style="border:3px solid #f1f1f1">
        <div >
            <div >
                <div ><div>5 star</div></div>
                <div >
                    <div >
                        <div ></div>
                    </div>
                </div>
                <div ><div><?php echo count_rate_data('5'); ?></div></div>
                <div ><div>4 star</div></div>
                <div >
                    <div >
                        <div ></div>
                    </div>
                </div>
                <div ><div><?php echo count_rate_data('4'); ?></div></div>
                <div ><div>3 star</div></div>
                <div >
                    <div >
                        <div ></div>
                    </div>
                </div>
                <div > <div><?php echo count_rate_data('3'); ?></div></div>
                <div ><div>2 star</div></div>
                <div >
                    <div >
                        <div ></div>
                    </div>
                </div>
                <div ><div><?php echo count_rate_data('2'); ?></div></div>
                <div ><div>1 star</div></div>
                <div >
                    <div >
                        <div ></div>
                    </div>
                </div>
                <div ><div><?php echo count_rate_data('1'); ?></div></div>
            </div>
        </div>
    </div>
</div>

<div >
<?php
$sql="SELECT * FROM item_rating ORDER by id DESC ";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
?>

<div >
    <div >
        <img src="user-dummy.png" width="75">
        <?php echo date('d M, Y',strtotime($row['created']));?></p>
    </div>
    <div >
        <span ><?php echo $row['rate_number'];?> <span  style="font-size: 12px;"></span></span> <?php echo $row['title'];?></p>
        <?php echo $row['comment'];?></p>
    </div>
</div>
<?php } ?>
</div>
<!-- Modal -->
<div  id="myModal" role="dialog">
    <div >

        <!-- Modal content-->
        <div >
            <div >
                <button type="button"  data-dismiss="modal">&times;</button>
            </div>
            <div >
                <div >
                    <span >User Rating</span>
                    <span ></span>
                    <span ></span>
                    <span ></span>
                    <span ></span>
                    <span ></span>
                </div>
                <form name="frmRating" id="frmRating">
                    <div >
                        <label for="txtTitle">Title:</label>
                        <input type="hidden" name="hdnRateNumber" id="hdnRateNumber">
                        <input type="text"  id="txtTitle" placeholder="Enter Title" name="txtTitle">
                    </div>
                    <div >
                        <label for="pwd">Comment:</label>
                        <pre name="txtComment" id="txtComment"  rows="10"></pre>
                    </div>
                    <button type="submit" >Submit</button>
                </form>
            </div>
            <div >
                <button type="button"  data-dismiss="modal">Close</button>
            </div>
        </div>

    </div>
</div>

</body>
</html>

Step3: Create a saveData.php file.

In this step, we will store data into the database such as rate number, title, and comment.

PHP
<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "rating";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}



if($_POST['txtTitle'] && $_POST['txtComment'])
{

    $rate = $_POST['hdnRateNumber'];
    $title = $_POST['txtTitle'];
    $comment = $_POST['txtComment'];
    $date = date('Y-m-d H:i:s');
    $sql = "INSERT INTO item_rating (rate_number,title,comment,created) VALUES ('".$rate."', '".$title."', '".$comment."','".$date."')";

    if (mysqli_query($conn, $sql) === TRUE) {
        echo "success";
    } else {
        echo "error";
    }

}

?>

Show Demo

Please follow and like us:

Hope this code and post will helped you for implement Star Rating System Using PHP and Jquery with ajax – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

3  +  2  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US