Tuesday, 12 March 2019

Ajax jQuery Based Star Rating System in Codeigniter



In this post, We will learn to make 5 Star Rating System in Codeigniter by using Ajax jQuery and Mysql database. Five Star Rating will allows to user to submit their review on any product or service or business unit is useful or not. User can send Live Rating on product and on web page it will get live result of result on web page without refresh of web page. Because here we will use Ajax with Codeigniter framework for developing Star Rating application. This feature is very common in most of the e-commerce who want to sale their product online. Based on rating user can get idea which product is good based on multiple user review.

In this system User can rate the business unit or product based on their quality of product or services, advantages of product etc. So, that rating will helpful to other user who want to use particular business unit service or buy product then based on other user review or rating new user will idea regarding of listed product on e-commerce site.

In this tutorial, we will use pure jquery and Ajax code for make Star rating in Codeigniter, here we have not use any jQuery plugin for implement star rating system in Codeigniter. This is dynamic star rating system, in which rating will be display on average rating of all user, which we have been make in Codeigniter using Ajax jQuery. In this system when use click on particular number of Star then Ajax request has been send to Codeigniter controller, which will insert rating data of particular product in Mysql table. This is simple Codeigniter Ajax based Star rating system script which will help you to developed 5 star rating feature in your Codeigniter web application. Below you can find complete step by step process of How to build Star rating in Codeigniter using Ajax jquery and Mysql.






Step 1 - Create Table


First, We have to create table in Mysql database, in this we have to make business and rating. This two table we will for build dynamic star rating system.


--
-- Database: `testing`
--

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

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

CREATE TABLE `business` (
  `id` int(11) NOT NULL,
  `business_name` varchar(300) NOT NULL,
  `address` text NOT NULL,
  `product` text NOT NULL
) ENGINE=InnoDB 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');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `business`
--
ALTER TABLE `business`
  ADD PRIMARY KEY (`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;

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

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

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

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

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `rating`
--
ALTER TABLE `rating`
  MODIFY `rating_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;


Step 2 - Database Connection


In second step, we have to make database connection in Codeigniter framework, for this we have to go to application/config/database.php and in this file we have to define Mysql database configuration details.


<?php

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'testing',
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);


?>


Step 3 - Controllers (Star_rating.php)


After this we have to make Star_rating.php controller file under application/controllers folder. In this class we have create following method for handle HTTP request.

__construnct() - This magic method will execute this block of code on every time when object of this class has been created.

index() - This is the root method of this Controllers class, when in browser we have enter base_url/star_rating, then it will execute this method which will load application/views/star_raing.php file as an output in browser.

fetch() - This method will display all business unit data on web page with Star rating. This method has received Ajax request for display all product details with star rating on web page.

insert() - This method will insert rating data by using models method. This method also received Ajax request for insert user rating data into Mysql table.


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Star_rating extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('star_rating_model');
 }

 function index()
 {
  $this->load->view('star_rating');
 }

 function fetch()
 {
  echo $this->star_rating_model->html_output();
 }

 function insert()
 {
  if($this->input->post('business_id'))
  {
   $data = array(
    'business_id'  => $this->input->post('business_id'),
    'rating'   => $this->input->post('index')
   );
   $this->star_rating_model->insert_rating($data);
  }
 }

}
?>


Step 4 - Models (Star_rating_model.php)


In Codeigniter framework, models class has been mainly used for do all Mysql database operation. This class method will be execute from controller class method. In this class we have use following make following method for star rating system.

get_business_data() - This method will return all business table data.

get_business_rating($business_id) - This method will return average rating of business based on $business_id argument.

html_output() - This method will convert all business data with rating in html format, this method has been called fetch method of Star_rating controllers class.

insert_rating() - This method will insert user rating data into rating Mysql table. This method has been called from insert() method of Star_rating controller.


<?php
class Star_rating_model extends CI_Model
{
 function get_business_data()
 {
  $this->db->order_by('id', 'DESC');
  return $this->db->get('business');
 }

 function get_business_rating($business_id)
 {
  $this->db->select('AVG(rating) as rating');
  $this->db->from('rating');
  $this->db->where('business_id', $business_id);
  $data = $this->db->get();
  foreach($data->result_array() as $row)
  {
   return $row["rating"];
  }
 }

 function html_output()
 {
  $data = $this->get_business_data();
  $output = '';
  foreach($data->result_array() as $row)
  {
   $color = '';
   $rating = $this->get_business_rating($row["id"]);
   $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:24px;">&#9733;</li>';
   }
   $output .= '</ul>
   <p>'.$row["address"].'</p>
   <label style="text-danger">'.$row["product"].'</label>
   <hr />
   ';
  }
  echo $output;
 }

 function insert_rating($data)
 {
  $this->db->insert('rating', $data);
 }
}

?>




Step 5 - Views (star_rating.php)


In Codeigniter framework views file has been used for display HTML output on web page. In this file we have use jQuery function for load business data on web page. In jQuery function, it has use Ajax request for display business and rating data on web page. Same way for insert rating data, here also we have use Ajax. So, all operation will be perform without refresh of web page. For star rating effect we have use jQuery code. This all source code you can find below.


<html>
<head>
    <title>Star Rating in Codeigniter using Ajax jQuery</title>
    
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.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.6/js/bootstrap.min.js"></script>
    
</head>
<body>
 <div class="container box">
  <h3 align="center">Star Rating in Codeigniter using Ajax jQuery</h3>
  <br />
  <span id="business_list"></span>
 </div>
</body>
</html>

<script>
$(document).ready(function(){

 load_data();

 function load_data()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>star_rating/fetch",
   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('click', '.rating', function(){
  var index = $(this).data('index');
  var business_id = $(this).data('business_id');
  $.ajax({
   url:"<?php echo base_url(); ?>star_rating/insert",
   method:"POST",
   data:{index:index, business_id:business_id},
   success:function(data)
   {
    load_data();
    alert("You have rate "+index +" out of 5");
   }
  })
 });

 $(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);
  for(var count = 1; count <= rating; count++)
  {
   $('#'+business_id+'-'+count).css('color', '#ffcc00');
  }
 });

});
</script>


This is the complete step by step process for create Star rating system in Codeigniter using Ajax jquery. So, you can learn something new in Codeigniter framework. If you want to see demo this post, you can find below demo link.






0 comments:

Post a Comment