Friday, 28 December 2018

Codeigniter Ajax CRUD Application using jQuery Bootgrid

If you have looking for make Single Page CRUD application in Codeigniter using Ajax, then this post will help you. Because in this post you can learn step by step or from scratch how to use jQuery Bootgrid plugin in Codeigniter with Ajax. jQuery Bootgrid plugin is a lightweight plugin, which is flexible, powerful grid plugin for load dynamic data using Ajax, it is also very customizable grid control mainly if you have use Bootstrap library. It is mainly used for display dynamic data using Ajax.


By using this plugin you can get following benifits:


  • Simple Header or Footer Navigation
  • Soriting Table Column Data
  • Live Searching or Filtering of Data
  • Pagination
  • Client Side Processing and Server Side Processing of Data

Once of our previouse post in which we have already covered jQuery Bootgrid Server Side Processing in PHP using Ajax. But here we have seen how to integrate Bootgrid Grid Plugin in Codeigniter Framework. Becase Codeigniter is PHP MVC framework, which is widely used by many web developers for their web development. So, If you are Codeigniter Web Developer then you have to know How to use Bootgrid Plugin with Codeigniter application. For this here we have make this tutorial. In this post we will Covered following CRUD operation with jQuery Bootgrid in Codeigniter using Ajax.


  • Do Server Side Processing and Load Data in jQuery Bootgrid Plugin in Codeigniter using Ajax
  • Add or Insert Data into Mysql in Codeigniter using Ajax with jQuery Bootgrid & Bootstrap Modal
  • Edit or Update Mysql Data in Codeigniter using Ajax with jQuery Bootgrid & Bootstrap Modal
  • Delete or Remove Data from Mysql in Codeigniter using Ajax with jQuery Bootgrid & Bootstrap Modal








Bootgrid.php(Controller)


First We have to make Bootgrid.php Controller under application/controllers folder. This class is mainly used for handle http request for perform Insert, Update, Delete and Read data Request. In this class, you can find following function.


index() - This is root function for this class, when in browser, we have write base url with this class then this function has been called. This function has load bootgrid.php view as output on browser.


fetch_data() - This function is received Ajax request from Bootgrid plugin for fetch data from mysql data. This function will convert data into Array format, and send to Bootgrid Ajax request in json string formate.


action() - This function is used for insert or add into mysql table using ajax. Because this function has received ajax request for insert data into mysql table.


fetch_single_data() - This function mainly fetch particular employee details based on value of employee id. This is for edit existing employee details.

delete_data() - This function is used for handle Ajax delete data request from jQuery Bootgrid Plugin in Codeigniter.



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

class Bootgrid extends CI_Controller {
 
 public function __construct()
 {
  parent::__construct();
  $this->load->model('bootgrid_model');
 }

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

 function fetch_data()
 {
  $data = $this->bootgrid_model->make_query();
  $array = array();
  foreach($data as $row)
  {
   $array[] = $row;
  }
  $output = array(
   'current'  => intval($_POST["current"]),
   'rowCount'  => 10,
   'total'   => intval($this->bootgrid_model->count_all_data()),
   'rows'   => $array
  );
  echo json_encode($output);
 }

 function action()
 {
  if($this->input->post('operation'))
  {
   $data = array(
    'name'   => $this->input->post('name'),
    'address'  => $this->input->post('address'),
    'gender'  => $this->input->post('gender'),
    'designation' => $this->input->post('designation'),
    'age'   => $this->input->post('age')
   );
   if($this->input->post('operation') == 'Add')
   {
    $this->bootgrid_model->insert($data);
    echo 'Data Inserted';
   }
   if($this->input->post('operation') == 'Edit')
   {
    $this->bootgrid_model->update($data, $this->input->post('employee_id'));
    echo 'Data Updated';
   }
  }
 }

 function fetch_single_data()
 {
  if($this->input->post('id'))
  {
   $data = $this->bootgrid_model->fetch_single_data($this->input->post('id'));
   foreach($data as $row)
   {
    $output['name'] = $row['name'];
    $output['address'] = $row['address'];
    $output['gender'] = $row['gender'];
    $output['designation'] = $row['designation'];
    $output['age'] = $row['age'];
   }
   echo json_encode($output);
  }
 }

 function delete_data()
 {
  if($this->input->post('id'))
  {
   $this->bootgrid_model->delete($this->input->post('id'));
   echo 'Data Deleted';
  }
 }
}

?>





Bootgrid_model.php(Models)


This class we have to make under application/models folder. This model class is mainly used for all type of database operation. In this class we have make following function for perform database related operation.


make_query() - This function is for fetch data from mysql table according to requirement for Bootgrid plugin. In this function we have make fetch data select query with Where clause for searching data, order_by clause for sorting data, and limit clause for pagination of data.


count_all_data() - This function return number of rows in employee table.


insert() - This mainly used for insert database operaton. It will make insert query, execute query and insert data into Database.


fetch_single_data() - This function is used for Select data of single employee based on value of $id variable.

update() - This function is for perform update or edit mysql database operation.

delete() - This function is for do mysql delete or remove data operation in Codeigniter.


application/models/Bootgrid_model.php


<?php
class Bootgrid_model extends CI_Model
{
 var $records_per_page = 10;
 var $start_from = 0;
 var $current_page_number = 1;

 function make_query()
 {
  if(isset($_POST["rowCount"]))
  {
   $this->records_per_page = $_POST["rowCount"];
  }
  else
  {
   $this->records_per_page = 10;
  }
  if(isset($_POST["current"]))
  {
   $this->current_page_number = $_POST["current"];
  }
  $this->start_from = ($this->current_page_number - 1) * $this->records_per_page;
  $this->db->select("*");
  $this->db->from("tbl_employee");
  if(!empty($_POST["searchPhrase"]))
  {
   $this->db->like('name', $_POST["searchPhrase"]);
   $this->db->or_like('address', $_POST["searchPhrase"]);
   $this->db->or_like('gender', $_POST["searchPhrase"]);
   $this->db->or_like('designation', $_POST["searchPhrase"]);
   $this->db->or_like('age', $_POST["searchPhrase"]);
  }
  if(isset($_POST["sort"]) && is_array($_POST["sort"]))
  {
   foreach($_POST["sort"] as $key => $value)
   {
    $this->db->order_by($key, $value);
   }
  }
  else
  {
   $this->db->order_by('id', 'DESC');
  }
  if($this->records_per_page != -1)
  {
   $this->db->limit($this->records_per_page, $this->start_from);
  }
  $query = $this->db->get();
  return $query->result_array();
 }

 function count_all_data()
 {
  $this->db->select("*");
  $this->db->from("tbl_employee");
  $query = $this->db->get();
  return $query->num_rows();
 }

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

 function fetch_single_data($id)
 {
  $this->db->where('id', $id);
  $query = $this->db->get('tbl_employee');
  return $query->result_array();
 }

 function update($data, $id)
 {
  $this->db->where('id', $id);
  $this->db->update('tbl_employee', $data);
 }

 function delete($id)
 {
  $this->db->where('id', $id);
  $this->db->delete('tbl_employee');
 }
}

?>


bootgrid.php(Views)


View file in Codeigniter framework is used for display HTML output on Web page. This bootgrid.php view file you can find under application/views folder. Here we have make HTML table as per Bootgrid plugin, and below you can find jQuery code, in which we have initialiaze jQuery Bootgrid plugin using bootgrid() method. Under this method we have trigger Ajax request for fetch data, and under this also we have make edit and delete button also under formatters option.



<html>
<head>
    <title>jQuery Bootgrid - Server Side Processing in Codeigniter</title>
    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-bootgrid/1.3.1/jquery.bootgrid.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-bootgrid/1.3.1/jquery.bootgrid.js"></script>  
</head>
<body>
    <div class="container box">
        <h3 align="center">jQuery Bootgrid - Server Side Processing in Codeigniter</h3><br />
        <div class="panel panel-default">
            <div class="panel-heading">
                <div class="row">
                    <div class="col-md-10">
                        <h3 class="panel-title">Employee List</h3>
                    </div>
                    <div class="col-md-2" align="right">
                        <button type="button" id="add_button" data-toggle="modal" data-target="#employeeModal" class="btn btn-info btn-xs">Add</button>
                    </div>
                </div>
                
            </div>
            <div class="panel-body">
                <div class="table-responsive">
                    <table id="employee_data" class="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th data-column-id="name">Name</th>
                                <th data-column-id="address">Address</th>
                                <th data-column-id="gender">Gender</th>
                                <th data-column-id="designation">Designation</th>
                                <th data-column-id="age">Age</th>
                                <th data-column-id="commands" data-formatter="commands" data-sortable="false">Action</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
       </div>
    </div>
</body>
</html>

<div id="employeeModal" class="modal fade">
    <div class="modal-dialog">
        <form method="post" id="employee_form">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Add Employee</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>Enter Name</label>
                        <input type="text" name="name" id="name" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Enter Address</label>
                        <textarea name="address" id="address" class="form-control"></textarea>
                    </div>
                    <div class="form-group">
                        <label>Select Gender</label>
                        <select name="gender" id="gender" class="form-control">
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Enter Designation</label>
                        <input type="text" name="designation" id="designation" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Enter Age</label>
                        <input type="text" name="age" id="age" class="form-control" />
                    </div>
                </div>
                <div class="modal-footer">
                    <input type="hidden" name="employee_id" id="employee_id" />
                    <input type="hidden" name="operation" id="operation" value="Add" />
                    <input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
                </div>
            </div>
        </form>
    </div>
</div>

<script type="text/javascript" language="javascript" >
$(document).ready(function(){
    
    var employeeTable = $('#employee_data').bootgrid({
        ajax:true,
        rowSelect: true,
        post:function()
        {
            return{
                id:"b0df282a-0d67-40e5-8558-c9e93b7befed"
            }
        },
        url:"<?php echo base_url(); ?>bootgrid/fetch_data",
        formatters:{
            "commands":function(column, row)
            {
                return "<button type='button' class='btn btn-warning btn-xs update' data-row-id='"+row.id+"'>Edit</button>" + "&nbsp; <button type='button' class='btn btn-danger btn-xs delete' data-row-id='"+row.id+"'>Delete</button>";
            }
        }
    });

    $('#add_button').click(function(){
        $('#employee_form')[0].reset();
        $('.modal-title').text("Add Employee");
        $('#action').val("Add");
        $('#operation').val("Add");
    });

    $(document).on('submit', '#employee_form', function(event){
        event.preventDefault();
        var name = $('#name').val();
        var address = $('#address').val();
        var gender = $('#gender').val();
        var designation = $('#designation').val();
        var age = $('#age').val();
        var form_data = $(this).serialize();
        if(name != '' && address != '' &&  gender != '' &&  designation != '' && age != '')
        {
            $.ajax({
                url:"<?php echo base_url(); ?>bootgrid/action",
                method:"POST",
                data:form_data,
                success:function(data)
                {
                    alert(data);
                    $('#employee_form')[0].reset();
                    $('#employeeModal').modal('hide');
                    $('#employee_data').bootgrid('reload');
                }
            });
        }
        else
        {
            alert("All Fields are Required");
        }
    });

    $(document).on("loaded.rs.jquery.bootgrid", function(){
        employeeTable.find('.update').on('click', function(event){
            var id = $(this).data('row-id');
            $.ajax({
                url:"<?php echo base_url(); ?>bootgrid/fetch_single_data",
                method:"POST",
                data:{id:id},
                dataType:"json",
                success:function(data)
                {
                    $('#employeeModal').modal('show');
                    $('#name').val(data.name);
                    $('#address').val(data.address);
                    $('#gender').val(data.gender);
                    $('#designation').val(data.designation);
                    $('#age').val(data.age);
                    $('.modal-title').text("Edit Employee Details");
                    $('#employee_id').val(id);
                    $('#action').val('Edit');
                    $('#operation').val('Edit');
                }
            });
        });

        employeeTable.find('.delete').on('click', function(event){
            if(confirm("Are you sure you want to delete this?"))
            {
                var id = $(this).data('row-id');
                $.ajax({
                    url:"<?php echo base_url(); ?>bootgrid/delete_data",
                    method:"POST",
                    data:{id:id},
                    success:function(data)
                    {
                        alert(data);
                        $('#employee_data').bootgrid('reload');
                    }
                });
            }
            else
            {
                return false;
            }
        });
    });
    
});
</script>


By using this post, you will make Codeigniter Ajax Single Page Application using jQeury Bootgrid plugin.

Friday, 21 December 2018

How to Load Dynamic Data in jQuery UI Tooltip using Ajax with PHP



If you are using jQuery as front-end for you web development, then this post will helpful. Because in this post we have covered topic like How to Load Ajax content in jQuery UI Tooltip plugin by using PHP script. Do you know what is tooltip, in a web development tooltip is a simple message that will fade in on web page when mouse cursor is move over any element like icon, image, hyperlink or simple text on webpage. But here we will load dynamic data into jQuery Tooltip by using PHP script with Ajax. By using Ajax, it will called request for fetch data from Mysql database, and convert into HTML format and load into tooltip plugin. That means all details will be appear on web page in tooltip while cursor move on particular element on web page.

By using Tooltip plugin, it will increase the UI of your web application. For make dynamic tooltip here we have use jQuery UI library tooltip plugin. By using tooltip, we can display hint or information of graphical UI. It is mainly initialize when cursor move hover on any element on web page. There many different ways we can use tooltips in web development, e.g. we can use tooltip for display for validation message on web page. There are different other way we can use tooltip. Tooltip is also benifit for form elements to display additional information for any HTML element in form.

Here we have take simple example of display student additional details in tooltip. When mouse move on any student name, in tooltip we have load that student image and other details like name phone number etc. For do this things we have use Ajax with jquery UI Tooltip plugin. For initialize tooltip plugin, here we have use tooltip() method. This method has been used to initialize tooltip plugin on HTML element. When mouse move on HTML element then here we have trigger Ajax request under content option callback function. This Ajax request send request to PHP script and fetch particular student data, convert into HTML format and lastly load under jQuery Tooltip plugin. For get complete source code of How to Load Dynamic Data in jQuery UI Tooltip using Ajax with PHP, below you can find complete source code.








Source Code


database_connection.php



<?php

//database_connection.php

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


?>


index.php



<!--
//index.php
!-->

<?php

include('database_connection.php');

$query = "SELECT * FROM tbl_student ORDER BY student_name ASC";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

?>

<html>  
    <head>  
        <title>How to Load Ajax Data in jQuery UI Tooltip using PHP</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">How to Load Ajax Data in jQuery UI Tooltip using PHP</a></h3><br />
   <br />
   <div class="row">
    <div class="col-md-3">
    
    </div>
    <div class="col-md-6">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">Student Details</h3>
      </div>
      <div class="panel-body">
       <div class="table-responsive">
        <table class="table table-striped table-bordered">
         <tr>
          <th>Student Name</th>
         </tr>
         <?php
         foreach($result as $row)
         {
          echo '<tr><td><b><a href="#" id="'.$row["student_id"].'" title=" ">'.$row["student_name"].'</a></b></td></tr>';
         }
         ?>
        </table>
       </div>
      </div>
     </div>
    </div>
   </div>
  </div>
    </body>  
</html>  




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

 $('a').tooltip({
  classes:{
   "ui-tooltip":"highlight"
  },
  position:{ my:'left center', at:'right+50 center'},
  content:function(result){
   $.post('fetch.php', {
    id:$(this).attr('id')
   }, function(data){
    result(data);
   });
  }
 });
  
});  
</script>





fetch.php



<?php

//fetch.php

include('database_connection.php');

if(isset($_POST["id"]))
{
 $query = "SELECT * FROM tbl_student WHERE student_id = '".$_POST["id"]."'";

 $statement = $connect->prepare($query);

 $statement->execute();

 $result = $statement->fetchAll();

 $output = '';

 foreach($result as $row)
 {
  $output .= '
  <img src="images/'.$row["image"].'" class="img-thumbnail" />
  <h4>Name - '.$row["student_name"].'</h4>
  <h4>Phone No. - '.$row["student_phone"].'</h4>
  ';
 }
 echo $output;
}

?>

Wednesday, 19 December 2018

How to Create Editable Select Box using jQuery in PHP



Hi, Guys in this post you can learn how to convert simple select box or combo box into editable select box by using jQuery with PHP script. By using editable dropdown list box user can easily filter list of option from large number of option, and he can select required option which he want to select at the time of form filling. This is required because if in select box there are large number of option then at the time of form filling by user, it will difficult for user for find right option from list of option. If select box is editable then user can type something under dropdown list box, and he can filter option according what he has type. By filtering options user can get proper option which he has find from list of option.

For make editable dropdown list box here we have use jQuery Editable Select plugin which you can find here from this Github link. From this link you can download this jQuery Editable Select plugin, and here you can also find complete documentation of this plugin also. Here in this post we will discuss how to make dynamic editable dropdown listbox by using this jQuery plugin with PHP. In short how to use jQuery Editable Select plugin with PHP script. Editable select box will add one feature in you web application, because it has reduce the work of user for finding option, and it is also increase the appearance of your website UI also. It will increase the functionality of your web based application.

Now question is arise how can convert simple dropdown list box to Editable dropdown list box by using this plugin. It is very simple, you have to just include library of this plugin in your web page, and after this in you have to called editableSelect() method on Select box attribute like class or id. Once this method has been called then it will initialize this plugin and it will convert select box to editable select box. In this post we have step by step describute how to make editable select box by using jQuery plugin, And how to use this editable select box in actual form based application using PHP. Below you can find PHP Mysql Crud operation application in which we have used editable dropdown list box, and how to use this feature with real web based application.









Source Code


database_connection.php



<?php

//database_connection.php

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

?>


index.php



<?php

//index.php

include('database_connection.php');

$query = "SELECT * FROM apps_countries ORDER BY country_name ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();


?>

<html>  
    <head>  
        <title>How to Make Editable Select Box using jQuery with PHP</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <link rel="stylesheet" href="jquery-editable-select.min.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="jquery-editable-select.min.js"></script>
  
    </head>  
    <body>  
        <div class="container">  
            <br />  
            <br />
   <br />
   <h2 align="center">How to Make Editable Select Box using jQuery with PHP</h2><br />
   <div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-6">
     <form method="post" id="sample_form">
      <div class="form-group">
       <label>Enter Name</label>
       <input type="text" name="name" id="name" class="form-control">
      </div>
      <div class="form-group">
       <label>Select Country</label>
       <select name="country" id="country" class="form-control">
       <?php
       foreach($result as $row)
       {
        echo '<option value="'.$row["country_name"].'">'.$row["country_name"].'</option>';
       }
       ?>
       </select>
      </div>
      <div class="form-group">
       <input type="hidden" name="action" id="action" value="add" />
       <input type="hidden" name="hidden_id" id="hidden_id" value="" /> 
       <input type="submit" name="Save" id="save" class="btn btn-success" value="Save" />
      </div>
     </form>
     <br />
     <div class="table-responsive">
      <table class="table table-bordered">
       <thead>
        <tr>
         <th>Name</th>
         <th>Country</th>
         <th>Edit</th>
        </tr>
       </thead>
       <tbody>
        
       </tbody>
      </table>
     </div>
    </div>
    
   </div>
   
   
   <br />
   <br />
   <br />
  </div>
    </body>  
</html>  
<script>  
$(document).ready(function(){
 
 fetch_data();
 
 function fetch_data()
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   success:function(data)
   {
    $('tbody').html(data);
   }
  });
 }
 
 $('#country').editableSelect();
 
 $('#sample_form').on('submit', function(event){
  event.preventDefault();
  
  if($('#name').val() == '')
  {
   alert("Enter Name");
   return false;
  }
  else if($('#country').val() == '')
  {
   alert("Select Country");
   return false;
  }
  else
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:$(this).serialize(),
    success:function(data)
    {
     alert(data);
     $('#sample_form')[0].reset();
     $('#action').val("add");
     $('#save').val('Save');
     fetch_data();
    }
   });
  }
 });
 
 $(document).on('click', '.edit', function(){
  var id = $(this).attr("id");
  var action = 'fetch_single';
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{id:id, action:action},
   dataType:'json',
   success:function(data)
   {
    $('#hidden_id').val(id);
    $('#name').val(data.name);
    $('#country').val(data.country);
    $('#action').val("edit");
    $('#save').val('Edit');
   }
  });
 });

});  
</script>




fetch.php



<?php

//fetch.php

include('database_connection.php');

$query = "SELECT * FROM sample_data ORDER BY id DESC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
 foreach($result as $row)
 {
  $output .= '
  <tr>
   <td>'.$row["name"].'</td>
   <td>'.$row["country"].'</td>
   <td><button type="button" name="edit" class="btn btn-primary btn-xs edit" id="'.$row["id"].'">Edit</button></td>
  </tr>
  ';
 }
}
else
{
 $output .= '
 <tr>
  <td colspan="3" align="center">Data not found</td>
 </tr>
 ';
}

echo $output;

?>


action.php



<?php

//action.php

include('database_connection.php');

if(isset($_POST["action"]))
{ 
 
 if($_POST["action"] == "add")
 {
  $data = array(
   ':name'  => $_POST["name"],
   ':country'  => $_POST["country"]
  );
  
  $query = "
  INSERT INTO sample_data (name, country) 
  VALUES (:name, :country)
  ";
  
  $statement = $connect->prepare($query);
  if($statement->execute($data))
  {
   echo 'Data Inserted';
  }
 }
 
 if($_POST["action"] == 'fetch_single')
 {
  $query = "SELECT * FROM sample_data WHERE id='".$_POST["id"]."'";
  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $output['name'] = $row["name"];
   $output['country'] = $row["country"];
  }
  echo json_encode($output);
 }
 
 if($_POST["action"] == "edit")
 {
  $data = array(
   ':name'  => $_POST["name"],
   ':country'  => $_POST["country"],
   ':id'  => $_POST["hidden_id"]
  );
  $query = "
  UPDATE sample_data 
  SET name = :name, country = :country 
  WHERE id = :id
  ";
  $statement = $connect->prepare($query);
  if($statement->execute($data))
  {
   echo 'Data Updated';
  }
 }
 
}

?>





Thursday, 13 December 2018

Live Table Add Edit Delete in Laravel using Ajax jQuery

Live Table Add Edit Delete in Laravel using Ajax jQuery - 1




Live Table Add Edit Delete in Laravel using Ajax jQuery - 2




Live Table Add Edit Delete in Laravel using Ajax jQuery - 3




Live Table Add Edit Delete in Laravel using Ajax jQuery - 4





If you are looking for web tutorial on how to make live table application in Laravel framework by using Ajax and jQuery. So, you are come on right place, here you can find step by step by not only web tutorial but also video tutorial on Live table Insert Update Delete mysql table records in Laravel framework with Ajax and jQuery. We all know Laravel is a robust PHP framework for develop enterprise level application from scratch with write small PHP code and reuse same code. If we have use Ajax jQuery with Laravel, then it will make standard level web application.

In this post we have make Single page Live table or Inline table application in Laravel by using Ajax jQuery. In this application we will perform all CRUD operation like Create, Read, Update and Delete mysql database data from Laravel Live table or Inline table application. In this application use can Create or Add or Insert new data into mysql table from table, User can Update or edit exisiting records of Mysql table from this Laravel Live table. User can delete or remove mysql data from this Application. He can perform all this operation without going to other page, but from single html table he can perform all CRUD operation. That means here we will make Single page Live table crud application in Laravel using Ajax and jQuery.

Most of the application there main function is insert, update, delete and read mysql data. So, here we have make Single page Inline table application in Laravel with Ajax jquery, and perform all function from single page without refresh of web page. So, it will increase the speed of your web application, and it will also advance feature in your application. It will improve your application efficiency also. So, if Laravel framework will work with Ajax and jQuery, then it will increase your web presense user interface from user also. Below you can find step by step source code of Live table insert update delete mysql data using Ajax jQuery in Laravel framework.






Source Code


First we have to create Livetable controller, for this we have to go command prompt, and write following command, this command will create LiveTable.php controller file under app/HTTP/controllers folder.


php artisan make:controller LiveTable


Livetable.php


Once controller has been created under app/HTTP/controllers folder. In this class you can find following method for handle HTTP request of Live table crud operation in Laravel.

index() - This is the root method of this class, it will load live_table.blade.php view file in browser, once this live table controller has been called in browser.

fetch_data() - This method has receieved ajax request for fetch data from live_table.blade.php file, and this function return data in json format.

add_data() - This method has received ajax request for insert or add new records in mysql table from live_table.blade.php file, and this method return response once data has been successfully inserted.

update_data() - This method is used for update or edit mysql table records using Ajax. Ajax request has been send from view file to this method for edit or update existing of data of Mysql in Laravel using Ajax.

delete_data() - This method has received delete mysql table data request from Ajax, This method mainly used for delete or remove data operation in Laravel. Once this method has delete data then it send back response to Ajax request.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class LiveTable extends Controller
{
    function index()
    {
        return view('live_table');
    }

    function fetch_data(Request $request)
    {
        if($request->ajax())
        {
            $data = DB::table('tbl_sample')->orderBy('id','desc')->get();
            echo json_encode($data);
        }
    }

    function add_data(Request $request)
    {
        if($request->ajax())
        {
            $data = array(
                'first_name'    =>  $request->first_name,
                'last_name'     =>  $request->last_name
            );
            $id = DB::table('tbl_sample')->insert($data);
            if($id > 0)
            {
                echo '<div class="alert alert-success">Data Inserted</div>';
            }
        } 
    }

    function update_data(Request $request)
    {
        if($request->ajax())
        {
            $data = array(
                $request->column_name       =>  $request->column_value
            );
            DB::table('tbl_sample')
                ->where('id', $request->id)
                ->update($data);
            echo '<div class="alert alert-success">Data Updated</div>';
        }
    }

    function delete_data(Request $request)
    {
        if($request->ajax())
        {
            DB::table('tbl_sample')
                ->where('id', $request->id)
                ->delete();
            echo '<div class="alert alert-success">Data Deleted</div>';
        }
    }
}
?>





livetable.blade.php


This is view file of Live table application in Laravel and this file you can find under resources/view/livetable.blade.php. This file is used for display output on browser. In this view file you can find html, jquery and Ajax source code for fetch and insert data into mysql table in Laravel. For fetch data using Ajax, here we have make fetch_data() jQuery function which send Ajax request to LiveTable.php controller. For Insert, Update and delete mysql data using Ajax also, here you can find jQuery code in which Ajax request has been send to LiveTable.php controller class.


<!DOCTYPE html>
<html>
 <head>
  <title>Live Table Insert Update Delete in Laravel 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>
  <br />
  <div class="container box">
   <h3 align="center">Live Table Insert Update Delete in Laravel using Ajax jQuery</h3><br />
   <div class="panel panel-default">
    <div class="panel-heading">Sample Data</div>
    <div class="panel-body">
     <div id="message"></div>
     <div class="table-responsive">
      <table class="table table-striped table-bordered">
       <thead>
        <tr>
         <th>First Name</th>
         <th>Last Name</th>
         <th>Delete</th>
        </tr>
       </thead>
       <tbody>
       
       </tbody>
      </table>
      {{ csrf_field() }}
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

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

 fetch_data();

 function fetch_data()
 {
  $.ajax({
   url:"/livetable/fetch_data",
   dataType:"json",
   success:function(data)
   {
    var html = '';
    html += '<tr>';
    html += '<td contenteditable id="first_name"></td>';
    html += '<td contenteditable id="last_name"></td>';
    html += '<td><button type="button" class="btn btn-success btn-xs" id="add">Add</button></td></tr>';
    for(var count=0; count < data.length; count++)
    {
     html +='<tr>';
     html +='<td contenteditable class="column_name" data-column_name="first_name" data-id="'+data[count].id+'">'+data[count].first_name+'</td>';
     html += '<td contenteditable class="column_name" data-column_name="last_name" data-id="'+data[count].id+'">'+data[count].last_name+'</td>';
     html += '<td><button type="button" class="btn btn-danger btn-xs delete" id="'+data[count].id+'">Delete</button></td></tr>';
    }
    $('tbody').html(html);
   }
  });
 }

 var _token = $('input[name="_token"]').val();

 $(document).on('click', '#add', function(){
  var first_name = $('#first_name').text();
  var last_name = $('#last_name').text();
  if(first_name != '' && last_name != '')
  {
   $.ajax({
    url:"{{ route('livetable.add_data') }}",
    method:"POST",
    data:{first_name:first_name, last_name:last_name, _token:_token},
    success:function(data)
    {
     $('#message').html(data);
     fetch_data();
    }
   });
  }
  else
  {
   $('#message').html("<div class='alert alert-danger'>Both Fields are required</div>");
  }
 });

 $(document).on('blur', '.column_name', function(){
  var column_name = $(this).data("column_name");
  var column_value = $(this).text();
  var id = $(this).data("id");
  
  if(column_value != '')
  {
   $.ajax({
    url:"{{ route('livetable.update_data') }}",
    method:"POST",
    data:{column_name:column_name, column_value:column_value, id:id, _token:_token},
    success:function(data)
    {
     $('#message').html(data);
    }
   })
  }
  else
  {
   $('#message').html("<div class='alert alert-danger'>Enter some value</div>");
  }
 });

 $(document).on('click', '.delete', function(){
  var id = $(this).attr("id");
  if(confirm("Are you sure you want to delete this records?"))
  {
   $.ajax({
    url:"{{ route('livetable.delete_data') }}",
    method:"POST",
    data:{id:id, _token:_token},
    success:function(data)
    {
     $('#message').html(data);
     fetch_data();
    }
   });
  }
 });


});
</script>


web.php


Once you have completed working on Controller class code and view file code, lastly you have to set route for LiveTable.php controller class. In this class we have create index(), fetch_data(), add_data(), update_data() and delete_data() method for fetch, insert and update data using Ajax in Laravel. For set route in Laravel, we have to go to routes/web.php file. And in this file we have to write following code for set route.


Route::get('/livetable', 'LiveTable@index');
Route::get('/livetable/fetch_data', 'LiveTable@fetch_data');
Route::post('/livetable/add_data', 'LiveTable@add_data')->name('livetable.add_data');
Route::post('/livetable/update_data', 'LiveTable@update_data')->name('livetable.update_data');
Route::post('/livetable/delete_data', 'LiveTable@delete_data')->name('livetable.delete_data');


Lastly for run Laravel Live table add edit delete mysql data application using Ajax jQuery, we have to go to command prompt, and write following command.


php artisan serve


Once this command has been run under command prompt in which you have already run composer command, then you will provide you this http://127.0.0.1:8000 link, and just run following link for run Live table application.


http://127.0.0.1:8000/livetable



Friday, 7 December 2018

How to Create Entire Div Clickable using jQuery



In this post you can find the solution of How to make whole Div tag clickable by using jQuery. There are many ways we can make Div tag clickable like by using CSS, HTML or javascript. But here we will seen how can use simple jQuery code to create whole Div clickable. In web development there are many places in which we have to put link on whole div tag not only single text. Then at that time we have put simple javascript in onclick attribute of div tag and make whole div tag clickable. Or by using CSS we have convert simple div tag to clickable div tag.

But by this method it has affect SEO score of our web page, because in html code we have add more attribute. But if we have use simple jQuery for this things then in single line of code it will convert div tag to clickable div tag without adding any extra tag in our html code. This source you can also implement other tag like span tag, html 5 article tag or any other tag which we can use in place of Div. So, by this code we not only convert Div tag to clickable tag, but also we can aslo use same code for convert other tag to clickable tag. Below you can find source code and online demo of How to make whole Div clickable by using jQuery.







Source Code



<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>How to make Whole Div Clickable using jquery</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 <style>
 .clickable
 {
  border:1px solid #ccc;
  cursor:pointer;
  padding-top:12px;
  padding-bottom:12px;
 }
 </style>
</head>
<body>
 <div class="container">
  <br />
  <h3 align="center">How to make Whole Div Clickable using jquery</h3>
  <br />
  
  <div class="row">
   <div class="col-md-4"></div>
   <div class="col-md-4 clickable">
    <img src="image.jpg" class="img-thumbnail" />
    <h3>Exporting Data into Multiple Excel sheets in PHP</h3>
    <p>If you are working with large amount of data and mainly we have use Excel and CSV file format for export data in web development. So, in this post we have describe how to split huge amount of mysql datable data and export into multiple excel or csv file by using PHPExcel library in PHP.</p>
    <a href="https://www.webslesson.info/2018/12/exporting-data-into-multiple-excel-sheets-in-php.html">Read more</a>
   </div>
   <div class="col-md-4"></div>
  </div>
  
 </div>
</body>
</html>
<script>
$(document).ready(function(){
 
 $('.clickable').click(function(){
  window.location = $(this).find("a").attr("href");
 });
 
});
</script>





Thursday, 6 December 2018

Exporting Data into Multiple Excel sheets in PHP



If you are working with large amount of data and mainly we have use Excel and CSV file format for export data in web development. So, in this post we have describe how to split huge amount of mysql datable data and export into multiple excel or csv file by using PHPExcel library in PHP. Suppose there are millions of data in your database, and that amount of data you cannot export into single excel file. At that time you have to divide your data into different files like what we have do in pagination. Like a pagination we have not load all data in single page, but we have divided same amount of data in different page. Same thing we have to do for export huge amount of data into multiple file using PHP script with PHPExcel library.

There are number of ways we can export database using PHP script can be done number of ways. But here we will export data into multiple excel file, and that file will be store under folder. By click on link, we can download multiple file one by one. So, here exporting data and downloading file has been divided, so chances of crash of our website will be very less.

The output of any web application is to get data in Excel, CSV or PDF format. If you want to make report from your web based application then data must be required in PDF format, but if you want to reuse data in other form, then data must be exported into Excel or CSV format. Because this two format data type is widely used for exchange between two web application. So, here in this post we have make this tutorial for export mysql data into multiple excel file using PHPExcel library in PHP script. Below you can find complete source code of this tutorial.







Source Code


index.php


This is index.php file, in this file first we have make database connection, and fetch data from customer table and display on web page. After this we have make form with input select option for select how many records you want to export in single Excel file and below you can find submit button. Once click on submit button then in that block first it will include PHPExcel library. After this first it will calculate how many file want to make from mysql database. After this here object of PHPEcel library has been created and start exporting mysql data in to multiple excel file. Once all data has been exported into multiple files then that file has been stored under folder. These all file download link will be display on web page, and for download file, below you can fine download.php file.


<?php

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

$query = "SELECT * FROM tbl_customer ORDER BY CustomerID";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

$total_rows = $statement->rowCount();

$download_filelink = '<ul class="list-unstyled">';

if(isset($_POST["export"]))
{
 require_once 'class/PHPExcel.php';
 $last_page = ceil($total_rows/$_POST["records_no"]);
 $start = 0;
 $file_number = 0;
 for($count = 0; $count < $last_page; $count++)
 {
  $file_number++;
  $object = new PHPExcel();
  $object->setActiveSheetIndex(0);
  $table_columns = array("Nos", "Customer Name", "Gender", "Address", "City", "Postal Code", "Country");
  $column = 0;
  foreach($table_columns as $field)
  {
   $object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);
   $column++;
  }

  $query = "
  SELECT * FROM tbl_customer ORDER BY CustomerID LIMIT ".$start.", ".$_POST["records_no"]."
  ";
  $statement = $connect->prepare($query);
  $statement->execute();
  $excel_result = $statement->fetchAll();
  $excel_row = 2;
  foreach($excel_result as $sub_row)
  {
   $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row, $excel_row-1);
   $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $sub_row["CustomerName"]);
   $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $sub_row["Gender"]);
   $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $sub_row["Address"]);
   $object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $sub_row["City"]);
   $object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $sub_row["PostalCode"]);
   $object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row, $sub_row["Country"]);
   $excel_row++;
  }
  $start = $start + $_POST["records_no"];
  $object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel5');
  $file_name = 'File-'.$file_number.'.xls';
  $object_writer->save($file_name);
  $download_filelink .= '<li><label><a href="download.php?filename='.$file_name.'" target="_blank">Download - '.$file_name.'</a></label></li>';
 }
 $download_filelink .= '</ul>';
}

?>
<html>
 <head>
  <title>Export Mysql Data into Multiple Excel File using PHP</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">Export Mysql Data into Multiple Excel File using PHP</h3>
   <br />
   <br />
   <form method="post">
    <div class="row">
     <div class="col-md-3" align="right"><label>No. of Records in Each File</label></div>
     <div class="col-md-2">
      <select name="records_no" class="form-control">
       <option value="5">5 per file</option>
       <option value="10">10 per file</option>
       <option value="15">15 per file</option>
      </select> 
     </div>
     <div class="col-md-2">
      <input type="submit" name="export" class="btn btn-success" value="Export to Excel" />
     </div>
     <div class="col-md-5">
      <?php echo $download_filelink; ?>
     </div>
    </div>
   </form>
   <br />
   <div class="table-responsive">
    <table id="customer_data" 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>
     <?php
     foreach($result as $row)
     {
      echo '
      <tr>
       <td>'.$row["CustomerName"].'</td>
       <td>'.$row["Gender"].'</td>
       <td>'.$row["Address"].'</td>
       <td>'.$row["City"].'</td>
       <td>'.$row["PostalCode"].'</td>
       <td>'.$row["Country"].'</td>
      </tr>
      ';
     }
     ?>
     </tbody>
    </table>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>



download.php


This file script is used for download exported excel file from folder. Once user click on excel download file then this file script has been execute and it will download particular excel file.


<?php

//download.php

if(isset($_GET["filename"]))
{
 if(file_exists($_GET["filename"]))
 {
  header("Content-Type: application/octet-stream");
  header("Content-Disposition: attachment; filename=" .  $_GET["filename"]);
  readfile($_GET["filename"]);
  unlink($_GET["filename"]);
 }
 else
 {
  echo 'No File Found';
 }
}

?>


Database


Run below SQL script, it will make customer table in your Database.


--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_customer`
--

CREATE TABLE `tbl_customer` (
  `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 `tbl_customer`
--

INSERT INTO `tbl_customer` (`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');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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



Download


Sunday, 2 December 2018

Ajax Codeigniter Product Filter with Pagination

Ajax Codeigniter Product Filter with Pagination - Part 1



Ajax Codeigniter Product Filter with Pagination - Part 2



Ajax Codeigniter Product Filter with Pagination - Part 3



Ajax Codeigniter Product Filter with Pagination - Part 4




This post is for Codeigniter web developer, because in this post we have make stylish product filter in Codeigniter framework by using Ajax jQuery. In this product filter user can filter product details by different filter which we have make by using Checkbox, and even product can be filter on two price range. For make price range filter here we have use jQuery UI slider plugin. This all operation has been done by using jQuery Ajax with Codeigniter framework.

In this Codeigniter ajax product filter we have also add pagination feature also. So, all product details will not be load on same page but it will be divided into different web page. So, it will reduce web page loading time. Here we have use Codeigniter pagination library for add pagination feature into Codeigniter product filter. If number of product load has been increase by limit to display on webpage, then in Codeigniter product filter it will automatically add pagination link. For go to one page to another page, here also we have use ajax also, so it will load another page product data without refresh of web page. So, this is Codeigniter product filter with pagination link using Ajax.


In most of the ecommerce website all product has been display with differnt product filter with pagination link. There are also for filter product data input type checkbox has been used for filter product data on different condition. Sameway for filter product data between two price, for this here also we have use jQuery UI library slider plugin. When we have slide price, and stop slide then it will fire ajax request for fetch data and display product data on web page which come between two price. These are basic functionality of Codeigniter Ajax Product filter with pagination feature. Below you can find complete source code of this tutorial.




Soruce Code


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `product`
--

CREATE TABLE `product` (
  `product_id` int(20) NOT NULL,
  `product_name` varchar(120) NOT NULL,
  `product_brand` varchar(100) NOT NULL,
  `product_price` decimal(8,2) NOT NULL,
  `product_ram` char(5) NOT NULL,
  `product_storage` varchar(50) NOT NULL,
  `product_camera` varchar(20) NOT NULL,
  `product_image` varchar(100) NOT NULL,
  `product_quantity` mediumint(5) NOT NULL,
  `product_status` enum('0','1') NOT NULL COMMENT '0-active,1-inactive'
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`product_id`, `product_name`, `product_brand`, `product_price`, `product_ram`, `product_storage`, `product_camera`, `product_image`, `product_quantity`, `product_status`) VALUES
(1, 'Honor 9 Lite (Sapphire Blue, 64 GB)  (4 GB RAM)', 'Honor', '14499.00', '4', '64', '13', 'image-1.jpeg', 10, '1'),
(2, '\r\nInfinix Hot S3 (Sandstone Black, 32 GB)  (3 GB RAM)', 'Infinix', '8999.00', '3', '32', '13', 'image-2.jpeg', 10, '1'),
(3, 'VIVO V9 Youth (Gold, 32 GB)  (4 GB RAM)', 'VIVO', '16990.00', '4', '32', '16', 'image-3.jpeg', 10, '1'),
(4, 'Moto E4 Plus (Fine Gold, 32 GB)  (3 GB RAM)', 'Moto', '11499.00', '3', '32', '8', 'image-4.jpeg', 10, '1'),
(5, 'Lenovo K8 Plus (Venom Black, 32 GB)  (3 GB RAM)', 'Lenevo', '9999.00', '3', '32', '13', 'image-5.jpg', 10, '1'),
(6, 'Samsung Galaxy On Nxt (Gold, 16 GB)  (3 GB RAM)', 'Samsung', '10990.00', '3', '16', '13', 'image-6.jpeg', 10, '1'),
(7, 'Moto C Plus (Pearl White, 16 GB)  (2 GB RAM)', 'Moto', '7799.00', '2', '16', '8', 'image-7.jpeg', 10, '1'),
(8, 'Panasonic P77 (White, 16 GB)  (1 GB RAM)', 'Panasonic', '5999.00', '1', '16', '8', 'image-8.jpeg', 10, '1'),
(9, 'OPPO F5 (Black, 64 GB)  (6 GB RAM)', 'OPPO', '19990.00', '6', '64', '16', 'image-9.jpeg', 10, '1'),
(10, 'Honor 7A (Gold, 32 GB)  (3 GB RAM)', 'Honor', '8999.00', '3', '32', '13', 'image-10.jpeg', 10, '1'),
(11, 'Asus ZenFone 5Z (Midnight Blue, 64 GB)  (6 GB RAM)', 'Asus', '29999.00', '6', '128', '12', 'image-12.jpeg', 10, '1'),
(12, 'Redmi 5A (Gold, 32 GB)  (3 GB RAM)', 'MI', '5999.00', '3', '32', '13', 'image-12.jpeg', 10, '1'),
(13, 'Intex Indie 5 (Black, 16 GB)  (2 GB RAM)', 'Intex', '4999.00', '2', '16', '8', 'image-13.jpeg', 10, '1'),
(14, 'Google Pixel 2 XL (18:9 Display, 64 GB) White', 'Google', '61990.00', '4', '64', '12', 'image-14.jpeg', 10, '1'),
(15, 'Samsung Galaxy A9', 'Samsung', '36000.00', '8', '128', '24', 'image-15.jpeg', 10, '1'),
(16, 'Lenovo A5', 'Lenovo', '5999.00', '2', '16', '13', 'image-16.jpeg', 10, '1'),
(17, 'Asus Zenfone Lite L1', 'Asus', '5999.00', '2', '16', '13', 'image-17.jpeg', 10, '1'),
(18, 'Lenovo K9', 'Lenovo', '8999.00', '3', '32', '13', 'image-18.jpeg', 10, '1'),
(19, 'Infinix Hot S3x', 'Infinix', '9999.00', '3', '32', '13', 'image-19.jpeg', 10, '1'),
(20, 'Realme 2', 'Realme', '8990.00', '4', '64', '13', 'image-20.jpeg', 10, '1'),
(21, 'Redmi Note 6 Pro', 'Redmi', '13999.00', '4', '64', '20', 'image-21.jpeg', 10, '1'),
(22, 'Realme C1', 'Realme', '7999.00', '2', '16', '15', 'image-22.jpeg', 10, '1'),
(23, 'Vivo V11', 'Vivo', '22900.00', '6', '64', '21', 'image-23.jpeg', 10, '1'),
(24, 'Oppo F9 Pro', 'Oppo', '23990.00', '6', '64', '18', 'image-24.jpg', 10, '1'),
(25, 'Honor 9N', 'Honor', '11999.00', '4', '64', '15', 'image-25.jpg', 10, '1'),
(26, 'Redmi 6A', 'Redmi', '6599.00', '2', '16', '13', 'image-26.jpeg', 10, '1'),
(27, 'InFocus Vision 3', 'InFocus', '7399.00', '2', '16', '13', 'image-27.jpeg', 10, '1'),
(28, 'Vivo Y69', 'Vivo', '11390.00', '3', '32', '16', 'image-28.jpeg', 10, '1'),
(29, 'Honor 7x', 'Honor', '12721.00', '4', '32', '18', 'image-29.jpeg', 10, '1'),
(30, 'Nokia 2.1', 'Nokia', '6580.00', '2', '1', '8', 'image-30.jpeg', 10, '1');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `product`
--
ALTER TABLE `product`
  ADD PRIMARY KEY (`product_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `product`
--
ALTER TABLE `product`
  MODIFY `product_id` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=31;




Controllers - Product_filter.php



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

class Product_filter extends CI_Controller {
 
 public function __construct()
 {
  parent::__construct();
  $this->load->model('product_filter_model');
 }

 function index()
 {
  $data['brand_data'] = $this->product_filter_model->fetch_filter_type('product_brand');
  $data['ram_data'] = $this->product_filter_model->fetch_filter_type('product_ram');
  $data['product_storage'] = $this->product_filter_model->fetch_filter_type('product_storage');
  $this->load->view('product_filter', $data);
 }

 function fetch_data()
 {
  sleep(1);
  $minimum_price = $this->input->post('minimum_price');
  $maximum_price = $this->input->post('maximum_price');
  $brand = $this->input->post('brand');
  $ram = $this->input->post('ram');
  $storage = $this->input->post('storage');
  $this->load->library('pagination');
  $config = array();
  $config['base_url'] = '#';
  $config['total_rows'] = $this->product_filter_model->count_all($minimum_price, $maximum_price, $brand, $ram, $storage);
  $config['per_page'] = 8;
  $config['uri_segment'] = 3;
  $config['use_page_numbers'] = TRUE;
  $config['full_tag_open'] = '<ul class="pagination">';
  $config['full_tag_close'] = '</ul>';
  $config['first_tag_open'] = '<li>';
  $config['first_tag_close'] = '</li>';
  $config['last_tag_open'] = '<li>';
  $config['last_tag_close'] = '</li>';
  $config['next_link'] = '&gt;';
  $config['next_tag_open'] = '<li>';
  $config['next_tag_close'] = '</li>';
  $config['prev_link'] = '&lt;';
  $config['prev_tag_open'] = '<li>';
  $config['prev_tag_close'] = '</li>';
  $config['cur_tag_open'] = "<li class='active'><a href='#'>";
  $config['cur_tag_close'] = '</a></li>';
  $config['num_tag_open'] = '<li>';
  $config['num_tag_close'] = '</li>';
  $config['num_links'] = 3;
  $this->pagination->initialize($config);
  $page = $this->uri->segment(3);
  $start = ($page - 1) * $config['per_page'];
  $output = array(
   'pagination_link'  => $this->pagination->create_links(),
   'product_list'   => $this->product_filter_model->fetch_data($config["per_page"], $start, $minimum_price, $maximum_price, $brand, $ram, $storage)
  );
  echo json_encode($output);
 }
  
}
?>


Models - Product_filter_model.php



<?php

class Product_filter_model extends CI_Model
{
 function fetch_filter_type($type)
 {
  $this->db->distinct();
  $this->db->select($type);
  $this->db->from('product');
  $this->db->where('product_status', '1');
  return $this->db->get();
 }

 function make_query($minimum_price, $maximum_price, $brand, $ram, $storage)
 {
  $query = "
  SELECT * FROM product 
  WHERE product_status = '1' 
  ";

  if(isset($minimum_price, $maximum_price) && !empty($minimum_price) &&  !empty($maximum_price))
  {
   $query .= "
    AND product_price BETWEEN '".$minimum_price."' AND '".$maximum_price."'
   ";
  }

  if(isset($brand))
  {
   $brand_filter = implode("','", $brand);
   $query .= "
    AND product_brand IN('".$brand_filter."')
   ";
  }

  if(isset($ram))
  {
   $ram_filter = implode("','", $ram);
   $query .= "
    AND product_ram IN('".$ram_filter."')
   ";
  }

  if(isset($storage))
  {
   $storage_filter = implode("','", $storage);
   $query .= "
    AND product_storage IN('".$storage_filter."')
   ";
  }
  return $query;
 }

 function count_all($minimum_price, $maximum_price, $brand, $ram, $storage)
 {
  $query = $this->make_query($minimum_price, $maximum_price, $brand, $ram, $storage);
  $data = $this->db->query($query);
  return $data->num_rows();
 }

 function fetch_data($limit, $start, $minimum_price, $maximum_price, $brand, $ram, $storage)
 {
  $query = $this->make_query($minimum_price, $maximum_price, $brand, $ram, $storage);

  $query .= ' LIMIT '.$start.', ' . $limit;

  $data = $this->db->query($query);

  $output = '';
  if($data->num_rows() > 0)
  {
   foreach($data->result_array() as $row)
   {
    $output .= '
    <div class="col-sm-4 col-lg-3 col-md-3">
     <div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px; height:450px;">
      <img src="'.base_url().'images/'. $row['product_image'] .'" alt="" class="img-responsive" >
      <p align="center"><strong><a href="#">'. $row['product_name'] .'</a></strong></p>
      <h4 style="text-align:center;" class="text-danger" >'. $row['product_price'] .'</h4>
      <p>Camera : '. $row['product_camera'].' MP<br />
      Brand : '. $row['product_brand'] .' <br />
      RAM : '. $row['product_ram'] .' GB<br />
      Storage : '. $row['product_storage'] .' GB </p>
     </div>
    </div>
    ';
   }
  }
  else
  {
   $output = '<h3>No Data Found</h3>';
  }
  return $output;
 }
}

?>




Views - product_filter.php



<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Product Filters in Codeigniter using Ajax</title>

    <!-- Bootstrap Core CSS -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <link href = "<?php echo base_url(); ?>asset/jquery-ui.css" rel = "stylesheet">
    <!-- Custom CSS -->
    <link href="<?php echo base_url(); ?>asset/style.css" rel="stylesheet">
</head>

<body>
    <!-- Page Content -->
    <div class="container">
        <div class="row">
            <div class="col-md-3">
    <br />
    <br />
    <br />
    <div class="list-group">
     <h3>Price</h3>
     <input type="hidden" id="hidden_minimum_price" value="0" />
                    <input type="hidden" id="hidden_maximum_price" value="65000" />
                    <p id="price_show">1000 - 65000</p>
                    <div id="price_range"></div>
                </div>    
                <div class="list-group">
     <h3>Brand</h3>
     <?php
                    foreach($brand_data->result_array() as $row)
                    {
                    ?>
                    <div class="list-group-item checkbox">
                        <label><input type="checkbox" class="common_selector brand" value="<?php echo $row['product_brand']; ?>"  > <?php echo $row['product_brand']; ?></label>
                    </div>
                    <?php
                    }
                    ?>
                </div>

    <div class="list-group">
     <h3>RAM</h3>
     <?php
                    foreach($ram_data->result_array() as $row)
                    {
                    ?>
                    <div class="list-group-item checkbox">
                        <label><input type="checkbox" class="common_selector ram" value="<?php echo $row['product_ram']; ?>" > <?php echo $row['product_ram']; ?> GB</label>
                    </div>
                    <?php
                    }
                    ?> 
                </div>
    
    <div class="list-group">
     <h3>Internal Storage</h3>
     <?php
                    foreach($product_storage->result_array() as $row)
                    {
                    ?>
                    <div class="list-group-item checkbox">
                        <label><input type="checkbox" class="common_selector storage" value="<?php echo $row['product_storage']; ?>"  > <?php echo $row['product_storage']; ?> GB</label>
                    </div>
                    <?php
                    }
                    ?> 
                </div>
            </div>

            <div class="col-md-9">
             <h2 align="center">Product Filters in Codeigniter using Ajax</h2>
    <br />
    <div align="center" id="pagination_link">

                </div>
    <br />
    <br />
    <br />
                <div class="row filter_data">

                </div>
            </div>
        </div>

    </div>
<style>
#loading
{
 text-align:center; 
 background: url('<?php echo base_url(); ?>asset/loader.gif') no-repeat center; 
 height: 150px;
}
</style>

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

    filter_data(1);

    function filter_data(page)
    {
        $('.filter_data').html('<div id="loading" style="" ></div>');
        var action = 'fetch_data';
        var minimum_price = $('#hidden_minimum_price').val();
        var maximum_price = $('#hidden_maximum_price').val();
        var brand = get_filter('brand');
        var ram = get_filter('ram');
        var storage = get_filter('storage');
        $.ajax({
            url:"<?php echo base_url(); ?>product_filter/fetch_data/"+page,
            method:"POST",
            dataType:"JSON",
            data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, brand:brand, ram:ram, storage:storage},
            success:function(data)
            {
                $('.filter_data').html(data.product_list);
                $('#pagination_link').html(data.pagination_link);
            }
        })
    }

    function get_filter(class_name)
    {
        var filter = [];
        $('.'+class_name+':checked').each(function(){
            filter.push($(this).val());
        });
        return filter;
    }

    $(document).on('click', '.pagination li a', function(event){
        event.preventDefault();
        var page = $(this).data('ci-pagination-page');
        filter_data(page);
    });

    $('.common_selector').click(function(){
        filter_data(1);
    });

    $('#price_range').slider({
        range:true,
        min:1000,
        max:65000,
        values:[1000,65000],
        step:500,
        stop:function(event, ui)
        {
            $('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
            $('#hidden_minimum_price').val(ui.values[0]);
            $('#hidden_maximum_price').val(ui.values[1]);
            filter_data(1);
        }

    });

});
</script>

</body>

</html>