Thursday, February 6, 2020

Full Text Search With Ajax In Laravel 6 Tutorial

Full Text Search With Ajax In Laravel 6 Tutorial

This is another release in Laravel 6. In this release, you will learn how to implement Laravel 6 full-text search using Ajax with the Laravel search package. Would you like to learn the full text search in your Laravel 6 application? In this case, this publication will help you learn this topic. Here in this publication we have presented a tutorial for creating a full text search with the package "nicolaslopezj / searchable" with Ajax under Laravel 6. Therefore, the user can retrieve search data on the website without updating the website, since we have used Ajax in the context of Laravel 6.

You need to know what full text search is. The full-text search is therefore a type of search method in which data is searched for in every request word in your database. Most search engines have used full-text search to find data in every search term and search result on the website. Browsing data in the database is more advanced.





We all know that data search is required on almost all dynamic websites that deal with the database. Therefore, the search function is required for every web-based application. However, if this search box has a full-text search function, viewers will see more meaningful search results based on their search query. If you've used Datatable, all words will be searched as a single word, while full-text searches will search and compete for each word to search for data in the database. So here we learned how to implement full text search in the context of Laravel 6 with Ajax with the composer package "nicolaslopezj / searchable".

  • Download the Laravel 6 framework
  • Download and install the search package
  • Establish database connection
  • Create a model
  • Create controller
  • Create a blade file view
  • Set the path for the driver method
  • Run the Laravel 6 application




Download Laravel 6 framework


To build a Laravel 6 application, you must first download and install the Laravel 6 framework. In this step of the Laravel 6 tutorial, you need to change to the command prompt and the directory where you want to load and install the Laravel framework 6. We have to write and execute the following command.



composer create-project --prefer-dist laravel/laravel laravel-6



This command downloads the Laravel 6 framework and installs it in the define directory.



Download and Install Searchable Package


In this Laravel 6 tutorial, we have to do a full-text search in the Laravel 6 application, for which we used the "nicolaslopezj / searchable" package. To do this, we have to go to the command prompt and run the following command. This command downloads this search package and installs it in the Laravel 6 application.


composer require nicolaslopezj/searchable


Make Database Connection


Before the connection to the MySQL database can be established, a table must first be created in the database. To do this, you need to run the following SQL script.



CREATE TABLE `full_text_searches` (
  `CustomerID` int(11) NOT NULL,
  `CustomerName` varchar(250) NOT NULL,
  `Gender` varchar(30) NOT NULL,
  `Address` text NOT NULL,
  `City` varchar(250) NOT NULL,
  `PostalCode` varchar(30) NOT NULL,
  `Country` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `full_text_searches`
--

INSERT INTO `full_text_searches` (`CustomerID`, `CustomerName`, `Gender`, `Address`, `City`, `PostalCode`, `Country`) VALUES
(1, 'Maria Anders', 'Female', 'Obere Str. 57', 'Berlin', '12209', 'Germany'),
(2, 'Ana Trujillo', 'Female', 'Avda. de la Construction 2222', 'Mexico D.F.', '5021', 'Mexico'),
(3, 'Antonio Moreno', 'Male', 'Mataderos 2312', 'Mexico D.F.', '5023', 'Mexico'),
(4, 'Thomas Hardy', 'Male', '120 Hanover Sq.', 'London', 'WA1 1DP', 'United Kingdom'),
(5, 'Paula Parente', 'Female', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(6, 'Wolski Zbyszek', 'Male', 'ul. Filtrowa 68', 'Walla', '01-012', 'Poland'),
(7, 'Matti Karttunen', 'Male', 'Keskuskatu 45', 'Helsinki', '21240', 'Finland'),
(8, 'Karl Jablonski', 'Male', '305 - 14th Ave. S. Suite 3B', 'Seattle', '98128', 'United States'),
(9, 'Paula Parente', 'Female', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(10, 'John Koskitalo', 'Male', 'Torikatu 38', 'Oulu', '90110', 'Finland'),
(39, 'Ann Devon', 'Female', '35 King George', 'London', 'WX3 6FW', 'United Kingdom'),
(38, 'Janine Labrune', 'Female', '67, rue des Cinquante Otages', 'Nantes', '44000', 'Finland'),
(37, 'Kathryn Segal', 'Female', 'Augsburger Strabe 40', 'Ludenscheid Gevelndorf', '58513', 'Germany'),
(36, 'Elizabeth Brown', 'Female', 'Berkeley Gardens 12 Brewery', 'London', 'WX1 6LT', 'United Kingdom'),
(30, 'Trina Davidson', 'Female', '1049 Lockhart Drive', 'Barrie', 'ON L4M 3B1', 'Canada'),
(31, 'Jeff Putnam', 'Male', 'Industrieweg 56', 'Bouvignies', '7803', 'Belgium'),
(32, 'Joyce Rosenberry', 'Female', 'Norra Esplanaden 56', 'HELSINKI', '380', 'Finland'),
(33, 'Ronald Bowne', 'Male', '2343 Shadowmar Drive', 'New Orleans', '70112', 'United States'),
(34, 'Justin Adams', 'Male', '45, rue de Lille', 'ARMENTIERES', '59280', 'France'),
(35, 'Pedro Afonso', 'Male', 'Av. dos Lusiadas, 23', 'Sao Paulo', '05432-043', 'Brazil'),
(100, 'Kathryn Segal', 'Female', 'Augsburger Strabe 40', 'Ludenscheid Gevelndorf', '58513', 'Germany'),
(101, 'Tonia Sayre', 'Female', '84 Haslemere Road', 'ECHT', 'AB32 2DY', 'United Kingdom'),
(102, 'Loretta Harris', 'Female', 'Avenida Boavista 71', 'SANTO AMARO', '4920-111', 'Portugal'),
(103, 'Sean Wong', 'Male', 'Rua Vito Bovino, 240', 'Sao Paulo-SP', '04677-002', 'Brazil'),
(104, 'Frederick Sears', 'Male', 'ul. Marysiuska 64', 'Warszawa', '04-617', 'Poland'),
(105, 'Tammy Cantrell', 'Female', 'Lukiokatu 34', 'HAMEENLINNA', '13250', 'Finland'),
(106, 'Megan Kennedy', 'Female', '1210 Post Farm Road', 'Norcross', '30071', 'United States'),
(107, 'Maria Whittaker', 'Female', 'Spresstrasse 62', 'Bielefeld Milse', '33729', 'Germany'),
(108, 'Dorothy Parker', 'Female', '32 Lairg Road', 'NEWCHURCH', 'HR5 5DR', 'United Kingdom'),
(109, 'Roger Rudolph', 'Male', 'Avenida Julio Saul Dias 78', 'PENAFIEL', '4560-470', 'Portugal'),
(110, 'Karen Metivier', 'Female', 'Rua Guimaraes Passos, 556', 'Sao Luis-MA', '65025-450', 'Brazil'),
(111, 'Charles Hoover', 'Male', 'Al. Tysiaclecia 98', 'Warszawa', '03-851', 'Poland'),
(112, 'Becky Moss', 'Female', 'Laivurinkatu 6', 'MIKKELI', '50120', 'Finland'),
(113, 'Frank Kidd', 'Male', '2491 Carson Street', 'Cincinnati', 'KY 45202', 'United States'),
(114, 'Donna Wilson', 'Female', 'Hallesches Ufer 69', 'Dettingen', '73265', 'Germany'),
(115, 'Lillian Roberson', 'Female', '36 Iolaire Road', 'NEW BARN', 'DA3 3FT', 'United Kingdom'),
(144, 'Stephen M. Menzies', 'Male', '577 Hartway Street', 'Bruie', '57325', 'United States'),
(143, 'Nikki G. Pascual', 'Female', '4291 Kinney Street', 'Agawam', '1001', 'United States'),
(141, 'Alpha A. Brookover', 'Female', '3542 Trainer Avenue', 'Kilbourne', '62655', 'United States'),
(142, 'Austin D. Salem', 'Male', '1184 Farland Street', 'Brockton', '2401', 'United States'),
(140, 'Bianca A. Carone', 'Female', '1777 Elkview Drive', 'Hialeah', '33012', 'United States'),
(139, 'Stephen M. Menzies', 'Male', '577 Hartway Street', 'Bruie', '57325', 'United States'),
(138, 'Nikki G. Pascual', 'Female', '4291 Kinney Street', 'Agawam', '1001', 'United States'),
(136, 'Alpha A. Brookover', 'Female', '3542 Trainer Avenue', 'Kilbourne', '62655', 'United States'),
(137, 'Austin D. Salem', 'Male', '1184 Farland Street', 'Brockton', '2401', 'United States'),
(145, 'Bianca A. Carone', 'Female', '1777 Elkview Drive', 'Hialeah', '33012', 'United States');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `full_text_searches`
--
ALTER TABLE `full_text_searches`
  ADD PRIMARY KEY (`CustomerID`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `full_text_searches`
--
ALTER TABLE `full_text_searches`
  MODIFY `CustomerID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=146;


Now we want to create a database connection in the context of Laravel 6. To do this, we have to open .env and define the configuration of the MySQL database in this file.


.env

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=

If you have carried out a full text search you will get the error SQL 1055. To avoid this error, we have to open the file config / database.php and change 'strict' => true to 'strict' in this file. => false. By changing this setting, you can avoid SQL error 1055.



<?php

----

 'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => false,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

-----

?>


Create Model


Here we used the Model class to query the generator database. To do this, we need to create the Model class, so we have to go to the command prompt and enter the following command.


php artisan make:model Full_text_search --migration



This command creates the model class in the app / Full_text_search.php folder. In this file we need to add SearchableTrait to the search package. Then we have to define the name of the table column in which we want to do the full text search, which you can see below.

app/Full_text_search.php

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Nicolaslopezj\Searchable\SearchableTrait;

class Full_text_search extends Model
{
    use Notifiable;
    use SearchableTrait;

    protected $searchable = [
        'columns' => [
            'full_text_searches.CustomerName'  => 10,
            'full_text_searches.Gender'   => 10,
            'full_text_searches.Address'   => 10,
            'full_text_searches.City'    => 10,
            'full_text_searches.PostalCode'  => 10,
            'full_text_searches.Country'   => 10,
            'full_text_searches.id'    => 10,
        ]
    ];

    protected $fillable = [
        'CustomerName', 'Gender', 'Address', 'City', 'PostalCode', 'Country',
    ];
}



Create Controller


To process the HTTP request, we need to create a controller in the Laravel 6 application. To create a controller here, we need to use the compser command and go to the command prompt and run the following command.


php artisan make:controller Full_text_search_Controller


This command creates a driver file called Full_text_search_Controller.php in the app / Http / Controllers folder. In this class, we first need to add a model class by adding code, e.g. B. with App \ Full_text_search; In this controller we have to do the following method.

index (): This is the root method of this controller. This method has a simple load file full_text_search.blade.php in the browser.

action (Request $ request): This method receives the Ajax request for full-text search data in the mysql database. First, this method has the verification that the incoming request is Ajax or not. If it is an Ajax request, only the rest of the code is executed. If this request is Ajax, it will be executed if it is blocked. When using the full-text search model with the search package, perform a full-text search based on the search query. After you receive the data, send it back to the Ajax request in json format.

app/Http/Controllers/Full_text_search_Controller.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Full_text_search;
use DataTables;

class Full_text_search_Controller extends Controller
{
    function index()
    {
     return view('full_text_search');
    }

    function action(Request $request)
    {
     if($request->ajax())
     {
      $data = Full_text_search::search($request->get('full_text_search_query'))->get();

      return response()->json($data);
     }
    }

    function normal_search(Request $request)
    {
        if($request->ajax())
        {
            $data = Full_text_search::latest()->get();
            return Datatables::of($data)->make(true);
        }
      
        return view('normal_search');
    }
}



Create View Blade File


To view the output in the browser, you need to create a blade file in the resources / views folder. Here we have created the file full_text_search.blade.php in this folder. In this file we first have to create the search data in the search field and then create a table. Then we have to write the Ajax request, which sends the Ajax request to the controller's action () method and receives full-text search data in json format. These are displayed in an HTML table and with jQuery on the website. This Ajax request is activated when we click the search button. The full source code of this file can be found below.

resources/views/full_text_search.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Full Text Search With Ajax In Laravel 6 Tutorial</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">    
     <br />
     <h3 align="center">Full Text Search With Ajax In Laravel 6 Tutorial</h3>
     <br />
     <div class="row">
      <div class="col-md-10">
       <input type="text" name="full_text_search" id="full_text_search" class="form-control" placeholder="Search" value="">
      </div>
      <div class="col-md-2">
       @csrf
       <button type="button" name="search" id="search" class="btn btn-success">Search</button>
      </div>
     </div>
     <br />
     <div class="table-responsive">
    <table class="table table-bordered table-striped">
        <thead>
         <tr>
            <th>Customer Name</th>
            <th>Gender</th>
            <th>Address</th>
                  <th>City</th>
                  <th>Postal Code</th>
                  <th>Country</th>
         </tr>
     </thead>
     <tbody></tbody>
    </table>
   </div>
        </div>
 </body>
</html>


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

 load_data('');

 function load_data(full_text_search_query = '')
 {
  var _token = $("input[name=_token]").val();
  $.ajax({
   url:"{{ route('full-text-search.action') }}",
   method:"POST",
   data:{full_text_search_query:full_text_search_query, _token:_token},
   dataType:"json",
   success:function(data)
   {
    var output = '';
    if(data.length > 0)
    {
     for(var count = 0; count < data.length; count++)
     {
      output += '<tr>';
      output += '<td>'+data[count].CustomerName+'</td>';
      output += '<td>'+data[count].Gender+'</td>';
      output += '<td>'+data[count].Address+'</td>';
      output += '<td>'+data[count].City+'</td>';
      output += '<td>'+data[count].PostalCode+'</td>';
      output += '<td>'+data[count].Country+'</td>';
      output += '</tr>';
     }
    }
    else
    {
     output += '<tr>';
     output += '<td colspan="6">No Data Found</td>';
     output += '</tr>';
    }
    $('tbody').html(output);
   }
  });
 }

 $('#search').click(function(){
  var full_text_search_query = $('#full_text_search').val();
  load_data(full_text_search_query);
 });

});
</script>





resources / views / normal_search.blade.php // This file should only understand how simple search works and how full-text search works.


<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Normal Search</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://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Normal Search in Datatables</h3>
     <br />
   <div class="table-responsive">
    <table class="table table-bordered table-striped" id="user_table">
           <thead>
            <tr>
                <th>Customer Name</th>
                    <th>Gender</th>
                    <th>Address</th>
                    <th>City</th>
                    <th>Postal Code</th>
                    <th>Country</th>
            </tr>
           </thead>
       </table>
   </div>
   <br />
   <br />
  </div>
 </body>
</html>


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

 $('#user_table').DataTable({
  processing: true,
  serverSide: true,
  ajax:{
   url: "{{ route('full-text-search.normal-search') }}",
  },
  columns:[
   {
    data: 'CustomerName',
    name: 'CustomerName'
   },
   {
    data: 'Gender',
    name: 'Gender'
   },
   {
        data: 'Address',
        name: 'Address'
      },
      {
        data: 'City',
        name: 'City'
      },
      {
        data: 'PostalCode',
        name: 'PostalCode'
      },
      {
        data: 'Country',
        name: 'Country'
      }
  ]
 });

});
</script>




Set Controller Method Route


In the Laravel 6 application we have to set the route of all controller methods. For this we have to open the routes / web.php file and in this file we have the defined route, which you can find below.



<?php

Route::get('full-text-search', 'Full_text_search_Controller@index');

Route::post('full-text-search/action', 'Full_text_search_Controller@action')->name('full-text-search.action');

Route::get('full-text-search/normal-search', 'Full_text_search_Controller@normal_search')->name('full-text-search.normal-search');

?>


Run Laravel 6 Application


After all the code is done, we finally need to start the Laravel 6 framework server. To do this, we have to go to the command prompt and enter the following command.


php artisan serve


This command starts the server and gives you the base URL of your application. For the previous test code, enter the following URL in your browser.


http://127.0.0.1:8000/full-text-search

So this is our complete Laravel 6 tutorial, where you will learn step by step how to use Ajax to create a full text search application with the "nicolaslopezj / searchable" package.


How To Make 5 Star Rating System in Codeigniter With JQuery, Ajax,PHP and MySQL

How To Make  5 Star Rating  System in Codeigniter With JQuery, Ajax,PHP and MySQL

In this post we learn how to create a 5 star rating system in Codeigniter using the Ajax jQuery and MySQL databases. With the five-star rating, the user can give his or her opinion about a product, a service or a business unit that is useful or not. The user can send a live review for the product and on the website you will get the live result of the result on the website without updating the website. Because here we are going to use Ajax with the Codeigniter framework to develop the Star Rating application. This function is very common among most e-commerce providers who want to sell your product online. Depending on the rating, the rating of multiple users can give the user an idea of which product is good.

In this system, the user can evaluate the business unit or the product based on the quality of his product or service, the advantages of the product, etc. Therefore, this qualification is useful for another user who wants to use a particular business area service or buy a product that is based on another user who is reviewing or evaluating the idea of the new user in relation to the product listed on the e-commerce website ,

In this tutorial, we use pure JQuery and Ajax code to evaluate stars in Codeigniter. Here we didn't use a jQuery plugin to implement the star rating system in Codeigniter. This is a dynamic star rating system where the rating is shown in the average rating of all users that we did in Codeigniter with Ajax jQuery. If you click on a specific star number in this system, the Ajax request was sent to the codeigniter controller, which inserts the qualification data of a specific product in the MySQL table. This is a simple star rating system script based on Ajax Codeigniter that will help you develop the 5 star rating feature in your Codeigniter web application. Below is the complete step-by-step process for creating star ratings in Codeigniter using Ajax jquery and MySQL.


Step 1 - Create Table


First we have to create a table in the MySQL database where we have to do business and qualify. We will do this two table to build a 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 the second step we have to establish the database connection as part of Codeigniter, for this we have to go to application / config / database.php and define the details of the database configuration in this file Mysql.



<?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


Then we have to create the driver file Star_rating.php in the folder application / controller. In this class we created the following method to process the HTTP request.

__construnct (): This magical method executes this block of code every time an object of this class is created.


index () - This is the root method of this controller class. If you have to enter base_url / star_rating in the browser, this method is executed, with which the file application / views / star_raing.php is loaded as output in the browser.

fetch (): This method shows all data of the business area on the website with star rating. This method received Ajax's request to display all details of the star-rated product on the website.

insert (): This method inserts qualification data using the model method. This method also received Ajax's request to insert user rating data into the 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


Under Codeigniter, the model class was mainly used to perform all operations in the MySQL database. This class method is carried out by the controller class method. In this class we have the make make following method for the star rating system.

get_business_data (): This method returns all data from the business table.


get_business_rating ($ business_id): This method returns the average rating of the company based on the argument $ business_id.

html_output () - This method converts all commercial data with classification in HTML format. This method was called the fetch method of the Star_rating controller class.

insert_rating (): This method inserts the user's rating data into the MySQL rating table. This method was called by the insert () method of the 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


The code file was used to display the HTML output on the website under Codeigniter. In this file we used the jQuery function to upload commercial data to the website. In the jQuery function, you used the Ajax requirement to display business and qualification data on the website. In the same way to insert qualification data, we also use Ajax here. Therefore, all operations are carried out without updating the website. We used the jQuery code for the star rating effect. This is all of the source code that you can find below.



<html>
<head>
    <title>How To Make  5 Star Rating  System in Codeigniter With JQuery, Ajax,PHP and MySQL </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">How To Make  5 Star Rating  System in Codeigniter With JQuery, Ajax,PHP and MySQL </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 guide to creating a star rating system in Codeigniter with Ajax JQuery. Then you can learn something new as part of Codeigniter. If you want to see the demo of this post, you can find the following demo link.


Form Validation with Ajax JQuery, JSON in Codeigniter

Form Validation with Ajax  JQuery, JSON  in Codeigniter

If you don't know how to check the form data using the Codeigniter form verification library with Ajax and get the response in JSON data type. In this publication you will find a form check in Codeignter with Ajax jQuery and JSON. To get to know the Codeigniter form validation library with Ajax, here we create the Ajax Codeigniter contact form to learn this topic.

We have already learned a lot from Codeigniter with Ajax. In this post we shared an interesting topic about codeigniter with Ajax. For information on creating Ajax-jQuery form validation, see Codeigniter. Using the Codeigniter forms validation library with Ajax, we get a success or error message in JSON format.

Every programmer knows that validation is a very important part of a web-based application or software process. Since you can find forms such as registration form, registration form, contact form, comment form etc. in every web application, we would like to validate the form data if we have not validated the form data. It is very dangerous for our web application. If you used the Codeigniter framework for your web-based application, Codeigniter has an extensive form validation library for validating form data that is used to configure server-side validation. However, server-side form data validation has an update page for each form submission. To prevent the form from being updated, we need to use Ajax with the Codeigniter form validation library. An Ajax request was made to the Codeigniter method, which uses the form validation library to perform validation rules on the form data. If a validation error occurs, you use the form_error () method to get the validation error, store it in an array, and send it back to the Ajax request in JSON format.



Therefore, the process of submitting the form is carried out without updating the website. It also tells you how to use Ajax to submit forms in Codeigniter without updating the website. To learn this topic here, we create a contact form with a field such as name, email address, subject and message. This contact form data is sent to the code signiter method using Ajax. In the Codeigiter method, you carry out various validation rules, e.g. B. Required field validation and email format validation using the Codeigiter Form Validation Library. And after the validation rules are successful, send a response to Ajax in JSON format. Below is the complete source code for validating the Ajax Codeigniter form.


Source Code


Form_validation.php (Controllers)



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

class Form_validation extends CI_Controller {

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

 function validation()
 {
  $this->load->library('form_validation');
  $this->form_validation->set_rules('name', 'Name', 'required');
  $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
  $this->form_validation->set_rules('subject', 'Subject', 'required');
  $this->form_validation->set_rules('message', 'Message', 'required');
  if($this->form_validation->run())
  {
   $array = array(
    'success' => '<div class="alert alert-success">Thank you for Contact Us</div>'
   );
  }
  else
  {
   $array = array(
    'error'   => true,
    'name_error' => form_error('name'),
    'email_error' => form_error('email'),
    'subject_error' => form_error('subject'),
    'message_error' => form_error('message')
   );
  }

  echo json_encode($array);
 }

}

?>


form_validation.php (Views)



<html>
<head>
    <title>Form Validation with Ajax  JQuery, JSON  in Codeigniter </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">
  <br />
  <h3 align="center">Form Validation with Ajax  JQuery, JSON  in Codeigniter </h3>
  <br />
  <div class="row">
   <div class="col-md-4">

   </div>
   <div class="col-md-4">
    <span id="success_message"></span>
    <form method="post" id="contact_form">
     <div class="form-group">
      <input type="text" name="name" id="name" class="form-control" placeholder="Name" />
      <span id="name_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <input type="text" name="email" id="email" class="form-control" placeholder="Email Address" />
      <span id="email_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <input type="text" name="subject" id="subject" class="form-control" placeholder="Subject">
      <span id="subject_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <textarea name="message" id="message" class="form-control" placeholder="Message" rows="6"></textarea>
      <span id="message_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <input type="submit" name="contact" id="contact" class="btn btn-info" value="Contact Us">
     </div>
    </form>
   </div>
   <div class="col-md-4"></div>
  </div>
 </div>
</body>
</html>
<script>
$(document).ready(function(){

 $('#contact_form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"<?php echo base_url(); ?>form_validation/validation",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   beforeSend:function(){
    $('#contact').attr('disabled', 'disabled');
   },
   success:function(data)
   {
    if(data.error)
    {
     if(data.name_error != '')
     {
      $('#name_error').html(data.name_error);
     }
     else
     {
      $('#name_error').html('');
     }
     if(data.email_error != '')
     {
      $('#email_error').html(data.email_error);
     }
     else
     {
      $('#email_error').html('');
     }
     if(data.subject_error != '')
     {
      $('#subject_error').html(data.subject_error);
     }
     else
     {
      $('#subject_error').html('');
     }
     if(data.message_error != '')
     {
      $('#message_error').html(data.message_error);
     }
     else
     {
      $('#message_error').html('');
     }
    }
    if(data.success)
    {
     $('#success_message').html(data.success);
     $('#name_error').html('');
     $('#email_error').html('');
     $('#subject_error').html('');
     $('#message_error').html('');
     $('#contact_form')[0].reset();
    }
    $('#contact').attr('disabled', false);
   }
  })
 });

});
</script>


How To Create And Download Zip File In Codeigniter

How To Create And Download  Zip File In Codeigniter

In this post we will discuss how we can generate a ZIP file with multiple files after saving this folder and finally download the generated ZIP file using the Codeigniter framework. Codeigniter is one of the best PHP frameworks that speeds up your web development process. Many web developers have used this framework to develop their web applications because it is a very popular PHP framework. Many utilities and built-in libraries have been provided to help you develop your web application very quickly. With this framework you can perform many tasks very easily. So here we also have a task on how to create a zip file under Codeigniter.


Codeigniter Zip Encoding Class


If you've used the Codeigniter framework, it's very easy to create a zip file. Because Codeigniter has its own integrated zip library. This class is used to generate zip files. Zip files can also be downloaded to our local computer. Now how to initialize this zip class. To do this, we need to write the following code.


$this->load->library('zip');


With the code above, you can initialize the Zipign code classiter. Then you can use another method of this class by calling the object $ this-> zip. Now we want to create a zip file of selected images from the image list. For this we use the following method of this zip library.

read_file (): This method reads the contents of a file and adds it to Zip.

add_data (): This method adds data to the zip file. It defines the file path and the data of this file.

archive (): This method writes the file to the specified directory. With this method, we need to define the name of the file with the full path.

download () - This method downloads the zip file created on our local computer. With this method we have to define the name of the zip file.

The Codeigniter Zip class method in particular helps us to generate a zip file, save it in a folder and download it to our local computer. Below is the full source code of this tutorial.


Source Code


Zip_file.php(Controllers)



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

class Zip_file extends CI_Controller {
 
 function index()
 {
  $directory = 'download';
  $data["images"] = glob($directory . "/*.jpg");
  $this->load->view('zip_file', $data);
 }

 function download()
 {
  if($this->input->post('images'))
  {
   $this->load->library('zip');
   $images = $this->input->post('images');
   foreach($images as $image)
   {
    $this->zip->read_file($image);
   }
   $this->zip->download(''.time().'.zip');
  }
 }

}

?>


zip_file.php



<html>
<head>
    <title>How To Create And Download  Zip File In Codeigniter</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">How To Create And Download  Zip File In Codeigniter</h3>
  <br />
  <form method="post" action="<?php echo base_url(); ?>zip_file/download">
  <?php
  foreach($images as $image)
  {
   echo '
   <div class="col-md-2" align="center" style="margin-bottom:24px;">
    <img src="'.base_url().''.$image.'" class="img-thumbnail img-responsive" />
     <br />
    <input type="checkbox" name="images[]" class="select" value="'.$image.'" />
   </div>
   ';
  }
  ?>
  <br />
  <div align="center">
   <input type="submit" name="download" class="btn btn-primary" value="Download" />
  </div>
  </form>
 </div>
</body>
</html>

<script>
$(document).ready(function(){
 $('.select').click(function(){
  if(this.checked)
  {
   $(this).parent().css('border', '5px solid #ff0000');
  }
  else
  {
   $(this).parent().css('border', 'none');
  }
 });
});
</script>