lundi 25 mai 2020

How to Display Star rating Count and Average Value n html website?

I'm trying to display star rating value though HTML page in database using html, php and JavaScript. For some reason it's not working, I've posted all the codes below.

here is index.html code

<html>
<head>
<title>Star Rating</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" crossorigin="anonymous"/>
<style>
/* Star Rating */
.rate {
float: left;
height: 46px;
text-align: left;
}
.rate:not(:checked) > input {
position:absolute;
/*top:-9999px;*/
display: none;
}
.rate:not(:checked) > label {
float:right;
width:1em;
overflow:hidden;
white-space:nowrap;
cursor:pointer;
font-size:40px;
color:#ccc;
}
.rate:not(:checked) > label:before {
/*content: '★ ';*/
content: "\2605";
}
.rate > input:checked ~ label, .rate input[checked="checked"] ~ label {
color: #ffc700;    
}
.rate:not(:checked) > label:hover,
.rate:not(:checked) > label:hover ~ label {
color: #deb217;  
}
.rate > input:checked + label:hover,
.rate > input:checked + label:hover ~ label,
.rate > input:checked ~ label:hover,
.rate > input:checked ~ label:hover ~ label,
.rate > label:hover ~ input:checked ~ label {
color: #c59b08;
}

.overall-rating{
width: 100%;
float: left;
font-size: 14px;
margin-top: 5px;
color: #8e8d8d;
}

.statusMsg{
font-size: 16px;
padding: 10px !important;
border: 1.5px dashed;
}
.statusMsg.errordiv{
color: #ff4040;
}
.statusMsg.succdiv{
color: #00bf6f;
}
</style>
</head>
<body>
<div class="container">
<div class="rate rating_star" postID="3" class="clearfix">
<input type="radio" id="star5" name="rating" value="5">
<label for="star5"></label>
<input type="radio" id="star4" name="rating" value="4">
<label for="star4"></label>
<input type="radio" id="star3" name="rating" value="3">
<label for="star3"></label>
<input type="radio" id="star2" name="rating" value="2">
<label for="star2"></label>
<input type="radio" id="star1" name="rating" value="1">
<label for="star1"></label>
</div>
<div class="overall-rating" >
(Average Rating <span id="avgrat" property="ratingValue"></span> Based on <span id="totalrat"  property="ratingCount">125</span> rating)&nbsp;<span id="msg" class=""></span>
</div>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/all.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" crossorigin="anonymous"></script>
<script>
$(function() {
$('.rate input').on('click', function(){
var postID = 3;
var ratingNum = $(this).val();

$.ajax({
type: 'POST',
url: 'rating.php',
data: 'postID='+postID+'&ratingNum='+ratingNum,
dataType: 'json',
success : function(resp) {
if(resp.status == 1){
let avgrat = data.average_rating;
let totalrat = data.rating_num;
$('#avgrat').text(resp.data.average_rating);
$('#totalrat').text(resp.data.rating_num);
}else if(resp.status == 2){
$('#msg').text("You are not allow to rate again.");
$("#msg").addClass("text-danger");
}

$( ".rate input" ).each(function() {
if($(this).val() <= parseInt(resp.data.average_rating)){
$(this).attr('checked', 'checked');
}else{
$(this).prop( "checked", false );
}
});
}
});
});
});
</script>
</body>
</html>

here rating.php code

<?php 
// Include the database config file 
include_once 'database.php'; 

if(!empty($_POST['postID']) && !empty($_POST['ratingNum'])){ 
    // Get posted data 
    $postID = $_POST['postID']; 
    $ratingNum = $_POST['ratingNum']; 

    // Current IP address 
    $userIP = $_SERVER['REMOTE_ADDR']; 

    // Check whether the user already submitted the rating for the same post 
    $query = "SELECT rating_number FROM cigatirating WHERE post_id = $postID AND user_ip = '".$userIP."'"; 
    $result = $db->query($query); 

    if($result->num_rows > 0){ 
        // Status 
        $status = 2; 
    }else{ 
        // Insert rating data in the database 
        $query = "INSERT INTO cigatirating (post_id,rating_number,user_ip) VALUES ('".$postID."', '".$ratingNum."', '".$userIP."')"; 
        $insert = $db->query($query); 

        // Status 
        $status = 1; 
    } 

    // Fetch rating details from the database 
    $query = "SELECT COUNT(rating_number) as rating_num, FORMAT((SUM(rating_number) / COUNT(rating_number)),1) as average_rating FROM cigatirating WHERE post_id = $postID GROUP BY (post_id)"; 
    $result = $db->query($query); 
    $ratingData = $result->fetch_assoc(); 

    $response = array( 
        'data' => $ratingData, 
        'status' => $status 
    ); 

    // Return response in JSON format 
    echo json_encode($response); 
} 
?>

db.php

<?php
    $dbHost = "localhost";
    $dbUsername = "root";
    $dbPassword = "";
    $dbname = "demorate";

    //Create Database Connection
    $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbname);

    //Check Connection
    if($db->connect_error){
        die("Connection failed: " . $db->connect_error);
    }
?>

rating.sql

CREATE TABLE `rating` (
  `id` int(11) NOT NULL,
  `post_id` int(11) NOT NULL,
  `rating_number` int(11) NOT NULL,
  `user_ip` varchar(20) NOT NULL COMMENT 'User IP Address',
  `submitted` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Now code is working very well but problem is how to display rating value ?




Aucun commentaire:

Enregistrer un commentaire