Stars Rating System With jQuery Ajax & PHP

Posted under :
Download the script Check the demo

This script will offer you a stars rating system ready to integrate to your aricle or media’s content on your website, the code control the rates with IP and store the user rate to the database with ajax and give a better user interface buttons working with jQuery.

This tutorial is much easy than you can expect, so here we start :

Mysql

In your database create a table named “wcd_rating” :

CREATE TABLE IF NOT EXISTS `wcd_rate` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_post` int(11) NOT NULL,
  `ip` varchar(40) NOT NULL,
  `rate` int(11) NOT NULL,
  `dt_rated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
)

index.php

Like in the index.php‘s file we will use the first rating bar example, for each star we create a div with the .rate-btn css class to show the image of the star
*the id attribute its the value of the rating choice

<div class="rate-ex1-cnt">
    <div id="1" class="rate-btn-1 rate-btn"></div>
    <div id="2" class="rate-btn-2 rate-btn"></div>
    <div id="3" class="rate-btn-3 rate-btn"></div>
    <div id="4" class="rate-btn-4 rate-btn"></div>
    <div id="5" class="rate-btn-5 rate-btn"></div>
</div>

For a better looking we add the javascript code that light the star on hover and the stars come before by add a new css class with a yellow color star

$('.rate-btn').hover(function(){
    $('.rate-btn').removeClass('rate-btn-hover');
    var therate = $(this).attr('id');
    for (var i = therate; i >= 0; i--) {
        $('.rate-btn-'+i).addClass('rate-btn-hover');
    };
});

By clicking in a star, a choice with a value is made, so with the javascript, we keep the the stars lighted, and we send the choices value and the id of the content via $.ajax() to store it in the database.

<?php $post_id = 'the post id'; ?>
$('.rate-btn').click(function(){    
    var therate = $(this).attr('id');
    var dataRate = 'act=rate&post_id=<?php echo $post_id; ?>&rate='+therate;
    $('.rate-btn').removeClass('rate-btn-active');
    for (var i = therate; i >= 0; i--) {
        $('.rate-btn-'+i).addClass('rate-btn-active');
    };
    $.ajax({
        type : "POST",
        url : "http://localhost/rating/ajax.php",  //change it with your own adress to the code
        data: dataRate,
        success:function(html){
        }
    });
});

ajax.php

Now we come the ajax.php part, here we wil check if the user has rate the content before with his ip, if ya we will update his rate, if its a new rate, ofcourse we add a new line
but before we call the config.php file to connect with our database.

require_once 'config.php';

if($_POST['act'] == 'rate'){
  //search if the user(ip) has already gave a note
  $ip = $_SERVER["REMOTE_ADDR"];
  $therate = $_POST['rate'];
  $thepost = $_POST['post_id'];

  $query = mysql_query("SELECT * FROM wcd_rate where ip= '$ip'  "); 
  while($data = mysql_fetch_assoc($query)){
    $rate_db[] = $data;
  }

  if(@count($rate_db) == 0 ){
    mysql_query("INSERT INTO wcd_rate (id_post, ip, rate)VALUES('$thepost', '$ip', '$therate')");
  }else{
    mysql_query("UPDATE wcd_rate SET rate= '$therate' WHERE ip = '$ip'");
  }
}

this is it, we are done with it :)

Now after storing the rate’s lines to the “wcd_rate” table we will retreive the data for the result and we come back to the index.php file for it.

index.php

If we will retreive the result of the rates, we have to include the ‘config.php’ to connect with the database

require_once 'config.php';

Then we calculate the numbers & the sum of the rate lines and we use it the calculate the percent of the rate

$query = mysql_query("SELECT * FROM wcd_rate"); 
while($data = mysql_fetch_assoc($query)){
    $rate_db[] = $data;
    $sum_rates[] = $data['rate'];
}
if(@count($rate_db)){
    $rate_times = count($rate_db);
    $sum_rates = array_sum($sum_rates);
    $rate_value = $sum_rates/$rate_times;
    $rate_bg = (($rate_value)/5)*100;
}else{
    $rate_times = 0;
    $rate_value = 0;
    $rate_bg = 0;
}
<h3>The content was rated <strong><?php echo $rate_times; ?></strong> times.</h3>
<hr>
<h3>The rating is at <strong><?php echo $rate_value; ?></strong> .</h3>
<hr>
<div class="rate-result-cnt">
    <div class="rate-bg" style="width:<?php echo $rate_bg; ?>%"></div>
    <div class="rate-stars"></div>
</div>

This is it for this tutorial, i hope you find the code useful, if yes :) don’t hesitate to subscribe to the newsletter, peace.



  • abderrahmen

    good job , if you do a video tutoriel it will be beter

  • DevMani Pandey

    This is greate tutorial no doubt. I require something more. I want to show rating for individual items fetched from database. Please help.

  • stefan

    How do you change so you vote on the same stars as you get the results from? I want 1 set of stars for both displaying the results and for voting…

  • Amar

    This is not working.Getting 2 warnings
    1.) Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in

    2)mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:Xindex.php on line 67

    • Mari G

      Use mysqli_connect instead http://php.net/manual/en/book.mysqli.php

      • Nate Mill

        NEED HELP!!!
        I want the stars to show this persons rate from stars. I want to make his rating highlighted even when that IP user refresh the page.

    • Atakan Aktoprak

      @mysql_connect(“sss”,””,””);
      not problem :)

  • Adam

    This is not working. I implemented exactly as demonstrated but the rate did not update in the database. it seems it is just images but database is not being updated.

    • Adam

      it seems that the $_post[] is not working.

  • Guest

    Grea

  • Adam

    Hi, Great script. How do you make it accommodate multillevel rating for a product.

    Example:
    Product A
    Overall rating: **
    Rating category 1: ***
    Rating category 2″: *
    etc..

  • kaushik

    thanks for your code

  • kaushik

    your system is perfectly working

  • rinku_y

    Let’s start with an easy example. Calculate the mean of the following set of numbers:

    1, 2, 3, 4, 5

    To do this, add up the numbers and divide by how many numbers you have (5 of them, in this case).

    mean = (1 + 2 + 3 + 4 + 5)/5

    mean = 15/5

    mean = 3

    Pretty easy, right?

  • rinku_y

    I found many problems in your logic

    if(@count($rate_db) == 0 ){
    mysql_query(“INSERT INTO wcd_rate (id_post, ip, rate)VALUES(‘$thepost’, ‘$ip’, ‘$therate’)”);
    }else{
    mysql_query(“UPDATE wcd_rate SET rate= ‘$therate’ WHERE ip = ‘$ip'”);
    }

    Here UPDATE wcd_rate SET rate= ‘$therate’ WHERE ip = ‘$ip but you should also pass $thepost heheheh

    Please provide a logical script instead this wrong script.

  • Alex Bond

    Very Useful! Thank you =)

  • It does not reset the rate when mouse leaves focus.

  • Moreover this control cannot be used more than once in a page. You should implement the click and hover event handlers so that they involve the siblings of the element where the mouse entered or clicked to.

  • Jacky Jax

    Simple yet powerful… Great Job!!

  • Quick update for the index.php

    Instead of queryig all the information from the DB and putting into an arrya to do the math you couls just call the following query:

    SELECT *,
    (select count(review_id) from rating where review_id =1) as rate_times,
    (select sum(rate)/rate_times from rating where review_id =1) as rate_value,
    (select (sum(rate)/rate_times)/5*100 from rating where review_id =1) as rate_bg
    from rating where review_id =1 limit 1

    Grettings, thanks for the ncie tutorial .

  • muthu

    how to remove first star color while without give rates

  • Nate Mill

    Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 36 bytes) in C:xampphtdocswidget_corpratingindex.php on line 68
    PLEASE HELP.

  • Nate Mill

    works perfect obey these steps if anyone had a problem

    1. Create a database like “wcd_rating”.

    2. Import the post_rating.sql file into the database.

    3. Open the config.php file and modify the $dbHost, $dbUsername, $dbPassword and $dbName variable value with your phpMyAdmin details.

    4. Run the index.php file and test the functionality.

  • Nate Mill

    NEED HELP!!!
    I want the stars to show this persons rate from stars. I want to make his rating highlighted even when that IP user refresh the page. please help

Be notified for new scripts