Review Star rating system with jQuery, Ajax and PHP Example

8

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.

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.

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

dbConfig.php File:

Database configuration and connection is done here.

index.php File:

You will need to include the jQuery library, rating.js and rating.css.

Attach tutspointer_rating_widget when the document is loaded. tutspointer_rating_widget() method is exists into the rating.js file. You can pass some options as key/value object to tutspointer_rating_widget() method.

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(). tutspointer_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.

When the page is loaded for first time, we will fetch the rating data from the database and display the overall rating.

Into the HTML we only need an input field with ID and custom attributes for defining the post ID.

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.

 

Leave A Reply

Your email address will not be published.