Thursday 2 November 2017

Dynamic Star Rating system by using PHP Script with Ajax Jquery



In this post we are going to learn new simple but very useful topic like how to make dynamic star rating system by using PHP Script with Ajax JQuery. By using this simple code you can easily developed Star rating system for in your web application. Here we will make Jquery Ajax rating system by using PHP script with Mysql. We will use very light code for developed dynamic star rating system.

Now a days if we have search for any company on Google, then in search we can see particular company details with rating display with search result. That rating defines the popularity of that company or product in market. If rating high that means is provides good services or in product rating, that product quality is good than other one. So from rating we can decide which one is good or bad. Even in movies we can see rating given by audience. If rating is low that means movies is not google and if rating high that means movies is good. So from rating we can get idea regarding any product, company, restaurant or even movie good or bad. We have to try or not.

So this type of system we are going to developed here by using PHP script with Ajax JQuery. Here we have two table like business and rating. In business that we have already insert some business data and rating details will be inserted into rating table. First we have load all business data on web page with star rating by using Ajax. After this we want to change color of star on mouse move and after mouse leave we want to reset particular business rating. So this things we have done by using Jquery code. And lastly we want to assign rating to particular business. So we have use Jquery click event, so when user give rating to particular business and he will click on particular number star then at that time we have use ajax request and it will send data to server and it will insert rating data into rating table. Based on available rating data, we have use average of all rating for display rating of particular business on web page. This way PHP Star rating by using Ajax Jquery has work. Below this you can find source code this tutorial with online demo also.








Source Code


index.php



<?php
//index.php
?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Star Rating System by using Ajax JQuery</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container" style="width:800px;">
   <h2 align="center">PHP Star Rating System by using Ajax JQuery</h2>
   <br />
   <span id="business_list"></span>
   <br />
   <br />
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 load_business_data();
 
 function load_business_data()
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   success:function(data)
   {
    $('#business_list').html(data);
   }
  });
 }
 
 $(document).on('mouseenter', '.rating', function(){
  var index = $(this).data("index");
  var business_id = $(this).data('business_id');
  remove_background(business_id);
  for(var count = 1; count<=index; count++)
  {
   $('#'+business_id+'-'+count).css('color', '#ffcc00');
  }
 });
 
 function remove_background(business_id)
 {
  for(var count = 1; count <= 5; count++)
  {
   $('#'+business_id+'-'+count).css('color', '#ccc');
  }
 }
 
 $(document).on('mouseleave', '.rating', function(){
  var index = $(this).data("index");
  var business_id = $(this).data('business_id');
  var rating = $(this).data("rating");
  remove_background(business_id);
  //alert(rating);
  for(var count = 1; count<=rating; count++)
  {
   $('#'+business_id+'-'+count).css('color', '#ffcc00');
  }
 });
 
 $(document).on('click', '.rating', function(){
  var index = $(this).data("index");
  var business_id = $(this).data('business_id');
  $.ajax({
   url:"insert_rating.php",
   method:"POST",
   data:{index:index, business_id:business_id},
   success:function(data)
   {
    if(data == 'done')
    {
     load_business_data();
     alert("You have rate "+index +" out of 5");
    }
    else
    {
     alert("There is some problem in System");
    }
   }
  });
  
 });

});
</script>


fetch.php



<?php

//fetch.php

$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');

$query = "
SELECT * FROM business ORDER BY id DESC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
 $rating = count_rating($row['id'], $connect);
 $color = '';
 $output .= '
 <h3 class="text-primary">'.$row['business_name'].'</h3>
 <ul class="list-inline" data-rating="'.$rating.'" title="Average Rating - '.$rating.'">
 ';
 
 for($count=1; $count<=5; $count++)
 {
  if($count <= $rating)
  {
   $color = 'color:#ffcc00;';
  }
  else
  {
   $color = 'color:#ccc;';
  }
  $output .= '<li title="'.$count.'" id="'.$row['id'].'-'.$count.'" data-index="'.$count.'"  data-business_id="'.$row['id'].'" data-rating="'.$rating.'" class="rating" style="cursor:pointer; '.$color.' font-size:16px;">&#9733;</li>';
 }
 $output .= '
 </ul>
 <p>'.$row["address"].'</p>
 <label style="text-danger">'.$row["product"].'</label>
 <hr />
 ';
}
echo $output;

function count_rating($business_id, $connect)
{
 $output = 0;
 $query = "SELECT AVG(rating) as rating FROM rating WHERE business_id = '".$business_id."'";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $total_row = $statement->rowCount();
 if($total_row > 0)
 {
  foreach($result as $row)
  {
   $output = round($row["rating"]);
  }
 }
 return $output;
}


?>


insert_rating.php



<?php

//fetch.php

$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');

if(isset($_POST["index"], $_POST["business_id"]))
{
 $query = "
 INSERT INTO rating(business_id, rating) 
 VALUES (:business_id, :rating)
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   ':business_id'  => $_POST["business_id"],
   ':rating'   => $_POST["index"]
  )
 );
 $result = $statement->fetchAll();
 if(isset($result))
 {
  echo 'done';
 }
}


?>


Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `business`
--

CREATE TABLE IF NOT EXISTS `business` (
  `id` int(11) NOT NULL,
  `business_name` varchar(300) NOT NULL,
  `address` text NOT NULL,
  `product` text NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `business`
--

INSERT INTO `business` (`id`, `business_name`, `address`, `product`) VALUES
(1, 'Fog Harbor Fish House', 'Fisherman''s Wharf, North Beach/Telegraph Hill\r\nPier 39\r\nSan Francisco, CA 94133\r\nPhone number (415) 421-2442', 'Seafood, Bars'),
(2, 'The House', 'North Beach/Telegraph Hill\r\n1230 Grant Ave\r\nSan Francisco, CA 94133\r\nPhone number (415) 986-8612', 'Asian Fusion'),
(3, 'Barnzu', 'Tenderloin\r\n711 Geary St\r\nSan Francisco, CA 94109\r\nPhone number (415) 525-4985', 'Korean, Tapas Bars'),
(4, 'Brenda French Soul Food', 'Tenderloin\r\n652 Polk St\r\nSan Francisco, CA 94102\r\nPhone number (415) 345-8100', 'Breakfast & Brunch, French, Soul Food'),
(5, 'The Salzburg', 'Russian Hill, North Beach/Telegraph Hill\r\n663 Union St\r\nSan Francisco, CA 94133', 'Austrian'),
(6, 'Marufuku Ramen', 'Lower Pacific Heights, Japantown\r\n1581 Webster St\r\nSan Francisco, CA 94115\r\nPhone number (415) 872-9786', 'Seafood, Seafood Markets, Live/Raw Food');

-- --------------------------------------------------------

--
-- Table structure for table `rating`
--

CREATE TABLE IF NOT EXISTS `rating` (
  `rating_id` int(11) NOT NULL,
  `business_id` int(11) NOT NULL,
  `rating` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `rating`
--

INSERT INTO `rating` (`rating_id`, `business_id`, `rating`) VALUES
(1, 6, 3),
(2, 6, 1),
(3, 6, 5),
(4, 6, 5),
(5, 6, 5),
(6, 5, 4),
(7, 5, 1),
(8, 5, 5),
(9, 4, 3),
(10, 5, 5),
(11, 5, 5),
(12, 4, 5),
(13, 3, 3),
(14, 6, 1),
(15, 3, 5),
(16, 3, 1),
(17, 3, 1),
(18, 3, 1),
(19, 4, 1),
(20, 5, 1),
(21, 5, 2),
(22, 6, 5),
(23, 2, 2),
(24, 2, 5),
(25, 2, 1);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `business`
--
ALTER TABLE `business`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `rating`
--
ALTER TABLE `rating`
  ADD PRIMARY KEY (`rating_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `business`
--
ALTER TABLE `business`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `rating`
--
ALTER TABLE `rating`
  MODIFY `rating_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=26;

7 comments: