HOW TO STAR RATING JQUERY AJAX PHP

HOW TO STAR RATING JQUERY AJAX PHP

HOW TO STAR RATING JQUERY AJAX PHP

0 Sales

Free

 

To get customer reviews about the product or service, Star Rating System is very useful. The consumer could rate the item using the rating system by selecting the star. It helps service providers improve their service based on the customer's rating. The 5 stars are mostly used to rate the rating system from 1 to 5. The Five-Star rating system, in addition to the manufacturer, allows the consumer to choose a quality product based on the other customers ' price.

 

The dynamic 5 Star Rating System can be easily implemented with the database using PHP and MySQL. If you want the review system to be integrated, star rating will definitely add an extra value to make it user-friendly. We'll show you how to create a 5-star rating system using jQuery, Ajax, PHP, and MySQL in this tutorial.

 

We will build a dynamic star rating system with PHP in the example script and incorporate it into the details page of the blog.

 

  • Collect and view specific post information from the server on the web page.

  • Add to the respective post a 5-star ranking.

  • Using jQuery and Ajax to request the user rating.

  • Place PHP and MySQL ranking number in the file.

  • Show the number of ratings and average star score.

 

Once you start building a star rating system, look at the structure of the files.

 

star_rating_system_php/

├── dbConfig.php

├── index.php

├── rating.php

├── js/

│   ├── jquery.min.js

└── css/

    └── style.css



 

Create Database Tables

In order to store the post and rating information in the database, two tables are required.

 

1. The following SQL builds a table of posts in the MySQL database with some simple fields.

 

CREATE TABLE `posts` (

 `id` int(11) NOT NULL AUTO_INCREMENT,

 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

 `content` text COLLATE utf8_unicode_ci NOT NULL,

 `created` datetime NOT NULL,

 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',

 PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

2. The following SQL creates a rating table in the MySQL database with a parent identification (post_id).

 

CREATE TABLE `rating` (

 `id` int(11) NOT NULL AUTO_INCREMENT,

 `post_id` int(11) NOT NULL,

 `rating_number` int(11) NOT NULL,

 `user_ip` varchar(20) COLLATE utf8_unicode_ci NOT NULL COMMENT 'User IP Address',

 `submitted` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,

 PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

Using PHP and MySQL, the following code is used to connect the database. Specify for your database credentials the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName).

 

<?php

// Database configuration

$dbHost     = "localhost";

$dbUsername = "root";

$dbPassword = "root";

$dbName     = "codexworld";


// Create database connection

$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);


// Check connection

if ($db->connect_error) {

    die("Connection failed: " . $db->connect_error);

}

Star Rating System in the Post Page (index.php)


 

We will display information about the particular post on the post page and add 5 Star rating for the corresponding post.

 

  • Based on a particular ID, collect the post and rating information from the database.

  • Show descriptions of the post and rating of stars to rate the post. Additionally, under the post name, the actual rating number and average rating are shown.

 

<?php

// Include the database config file

include_once 'dbConfig.php';


$postID = 1; // It will be changed with dynamic value


// Fetch the post and rating info from database

$query = "SELECT p.*, COUNT(r.rating_number) as rating_num, FORMAT((SUM(r.rating_number) / COUNT(r.rating_number)),1) as average_rating FROM posts as p LEFT JOIN rating as r ON r.post_id = p.id WHERE p.id = $postID GROUP BY (r.post_id)";

$result = $db->query($query);

$postData = $result->fetch_assoc();

?>

Submit Rating Number:

The rating number will be added to the server-side script via Ajax request once the user clicks on the star.

<div class="container">

    <h1><?php echo $postData['title']; ?></h1>

    <div class="rate">

        <input type="radio" id="star5" name="rating" value="5" <?php echo ($postData['average_rating'] >= 5)?'checked="checked"':''; ?>>

        <label for="star5"></label>

        <input type="radio" id="star4" name="rating" value="4" <?php echo ($postData['average_rating'] >= 4)?'checked="checked"':''; ?>>

        <label for="star4"></label>

        <input type="radio" id="star3" name="rating" value="3" <?php echo ($postData['average_rating'] >= 3)?'checked="checked"':''; ?>>

        <label for="star3"></label>

        <input type="radio" id="star2" name="rating" value="2" <?php echo ($postData['average_rating'] >= 2)?'checked="checked"':''; ?>>

        <label for="star2"></label>

        <input type="radio" id="star1" name="rating" value="1" <?php echo ($postData['average_rating'] >= 1)?'checked="checked"':''; ?>>

        <label for="star1"></label>

    </div>

    <div class="overall-rating">

        (Average Rating <span id="avgrat"><?php echo $postData['average_rating']; ?></span>

        Based on <span id="totalrat"><?php echo $postData['rating_num']; ?></span> rating)</span>

    </div>

    <div class="content"><?php echo $postData['content']; ?></div>

</div>

Include the jQuery library to use Ajax.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

Initiate Ajax request for the insertion of the database to post the rating number to the server-side script (rating.php).

 

  • Get the Post Data ID.

  • Get the rating number from the radio input selected.

  • Send rating number and post ID using jQuery Ajax to rating.php script.

  • Update the rating number and average rating data based on the response.

 

<script>

$(function() {

    $('.rate input').on('click', function(){

        var postID = <?php echo $postData['id']; ?>;

        var ratingNum = $(this).val();


        $.ajax({

            type: 'POST',

            url: 'rating.php',

            data: 'postID='+postID+'&ratingNum='+ratingNum,

            dataType: 'json',

            success : function(resp) {

                if(resp.status == 1){

                    $('#avgrat').text(resp.data.average_rating);

                    $('#totalrat').text(resp.data.rating_num);


                    alert('Thanks! You have rated '+ratingNum+' to "<?php echo $postData['title']; ?>"');

                }else if(resp.status == 2){

                    alert('You have already rated to "<?php echo $postData['title']; ?>"');

                }


                $( ".rate input" ).each(function() {

                    if($(this).val() <= parseInt(resp.data.average_rating)){

                        $(this).attr('checked', 'checked');

                    }else{

                        $(this).prop( "checked", false );

                    }

                });

            }

        });

    });

});

</script>



 

Save Rating Data in the Database (rating.php)


 

The Ajax request calls the rating.php file to insert rating number into the database.

 

  • Using PHP $POST method to retrieve the post ID and rating count.

  • Using $SERVER['REMOTE ADDR'] to get the latest IP address.

  • Test the submission of duplicate score based on the Post ID and IP address.

  • Insert in the database rating detail.

  • Fetch database rating data.

  • Give back the answer in JSON format.

 

<?php

// Include the database config file

include_once 'dbConfig.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 rating 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 rating (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 rating 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);

}

?>

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : May 14, 2020

Updated Date : May 14, 2020

Ratings

Comments : 0

Downloads : 0