PHP 5 Star Rating system with jQuery And AJAX

11-Apr-2023

.

Admin

PHP 5 Star Rating system with jQuery And AJAX

Hi Guys

In this blog, I will learn you how to create 5 star rating system with jquery, ajax, and php. We will show example of php 5 star rating system with jquery and ajax.The star rating bar allows the user to submit his thoughts on whether the content or product is useful or not. This also gives the administrator a view of how well its item is performing.

Whenever the user changes the rating then send an AJAX request to save the user currently rating status on the MySQL database table with PHP.

Here, I will give you full example for simply display 5 star rating system with jquery, ajax, and php. as bellow.

1: Create Table


I n this step, I will create mysql in two table create posts and post_rating.

posts Table

CREATE TABLE `posts` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`title` varchar(100) NOT NULL,

`content` text NOT NULL,

`link` varchar(255) NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

post_rating Table

CREATE TABLE IF NOT EXISTS `post_rating` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`userid` int(11) NOT NULL,

`postid` int(11) NOT NULL,

`rating` int(2) NOT NULL,

`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2: Configuration

Now In this step,I will Create a config.php for the database connection.

$host = "localhost"; /* Host name */

$user = "root"; /* User */

$password = ""; /* Password */

$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);

// Check connection

if (!$con) {

die("Connection failed: " . mysqli_connect_error());

}

3:HTML & PHP

In this setp,I will create php & html.file.load jquery bar rating plugin script with jquery library and also load a font awesome theme css with font awesome cdn file.

i have fixed the userid to 4 which you can replace with the $_session variable. fetch all records from the posts table.

get user rating on the post and average of the post.

create a layout to show title and content.

using <select> element to show the star rating on the screen. defined data-id attribute to get element id on the selection in the script.

set the previously selected rating by calling barrating() method where pass rating value on the set.

<?php include "config.php"; ?>

<!-- CSS -->

<link href="style.css" type="text/css" rel="stylesheet" />

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css">

<link href='jquery-bar-rating-master/dist/themes/fontawesome-stars.css' rel='stylesheet' type='text/css'>

<!-- Script -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>

<script src="jquery-bar-rating-master/dist/jquery.barrating.min.js" type="text/javascript"></script>

<div class="content">

<?php

$userid = 4;

$query = "SELECT * FROM posts";

$result = mysqli_query($con,$query);

while($row = mysqli_fetch_array($result)){

$postid = $row['id'];

$title = $row['title'];

$content = $row['content'];

$link = $row['link'];

// User rating

$query = "SELECT * FROM post_rating WHERE postid=".$postid." and userid=".$userid;

$userresult = mysqli_query($con,$query) or die(mysqli_error());

$fetchRating = mysqli_fetch_array($userresult);

$rating = $fetchRating['rating'];

// get average

$query = "SELECT ROUND(AVG(rating),1) as averageRating FROM post_rating WHERE postid=".$postid;

$avgresult = mysqli_query($con,$query) or die(mysqli_error());

$fetchAverage = mysqli_fetch_array($avgresult);

$averageRating = $fetchAverage['averageRating'];

if($averageRating <= 0){

$averageRating = "No rating yet.";

}

?>

<div class="post">

<h1><a href='<?php echo $link; ?>' class='link' target='_blank'><?php echo $title; ?></a></h1>

<div class="post-text">

<?php echo $content; ?>

</div>

<div class="post-action">

<!-- Rating -->

<select class='rating' id='rating_<?php echo $postid; ?>' data-id='rating_<?php echo $postid; ?>'>

<option value="1" >1</option>

<option value="2" >2</option>

<option value="3" >3</option>

<option value="4" >4</option>

<option value="5" >5</option>

</select>

<div style='clear: both;'></div>

Average Rating : <span id='avgrating_<?php echo $postid; ?>'><?php echo $averageRating; ?></span>

<!-- Set rating -->

<script type='text/javascript'>

$(document).ready(function(){

$('#rating_<?php echo $postid; ?>').barrating('set',<?php echo $rating; ?>);

});

</script>

</div>

</div>

<?php

}

?>

</div>

4: CSS

.content{

border: 0px solid black;

border-radius: 3px;

padding: 5px;

margin: 0 auto;

width: 50%;

}

.post{

border-bottom: 1px solid black;

padding: 10px;

margin-top: 10px;

margin-bottom: 10px;

}

.post:last-child{

border: 0;

}

.post h1{

font-weight: normal;

font-size: 30px;

}

.post a.link{

text-decoration: none;

color: black;

}

.post-text{

letter-spacing: 1px;

font-size: 15px;

font-family: serif;

color: gray;

text-align: justify;

}

.post-action{

margin-top: 15px;

margin-bottom: 15px;

}

.like,.unlike{

border: 0;

background: none;

letter-spacing: 1px;

color: lightseagreen;

}

.like,.unlike:hover{

cursor: pointer;

}

5: PHP

In this step I will Create a rating_ajax.php file.

Check for a postid entry by the user in post_rating Table. If a record exists then update the rating otherwise insert a new record.

Calculate the average rating on the $postid and return a JSON response.

<?php

include "config.php";

$userid = 4; // User id

$postid = $_POST['postid'];

$rating = $_POST['rating'];

// Check entry within table

$query = "SELECT COUNT(*) AS cntpost FROM post_rating WHERE postid=".$postid." and userid=".$userid;

$result = mysqli_query($con,$query);

$fetchdata = mysqli_fetch_array($result);

$count = $fetchdata['cntpost'];

if($count == 0){

$insertquery = "INSERT INTO post_rating(userid,postid,rating) values(".$userid.",".$postid.",".$rating.")";

mysqli_query($con,$insertquery);

}else {

$updatequery = "UPDATE post_rating SET rating=" . $rating . " where userid=" . $userid . " and postid=" . $postid;

mysqli_query($con,$updatequery);

}

// get average

$query = "SELECT ROUND(AVG(rating),1) as averageRating FROM post_rating WHERE postid=".$postid;

$result = mysqli_query($con,$query) or die(mysqli_error());

$fetchAverage = mysqli_fetch_array($result);

$averageRating = $fetchAverage['averageRating'];

$return_arr = array("averageRating"=>$averageRating);

echo json_encode($return_arr);

6: Script

In this step,Initialize barrating() on class='rating'. Define theme and onSelect option.

The onSelect triggers when a star rating is been changed. Get the element id and split it to get the postid.

Send an AJAX request where pass postid and value variables as data.

On successful callback update the average value on the element with the response.

$(function() {

$('.rating').barrating({

theme: 'fontawesome-stars',

onSelect: function(value, text, event) {

// Get element id by data-id attribute

var el = this;

var el_id = el.$elem.data('id');

// rating was selected by a user

if (typeof(event) !== 'undefined') {

var split_id = el_id.split("_");

var postid = split_id[1]; // postid

// AJAX Request

$.ajax({

url: 'rating_ajax.php',

type: 'post',

data: {postid:postid,rating:value},

dataType: 'json',

success: function(data){

// Update average

var average = data['averageRating'];

$('#avgrating_'+postid).text(average);

}

});

}

}

});

});

It will help you..

#PHP

#Jquery

#Html

#Css