Live Search Using Jquery Ajax, Php Codeigniter and Mysql-2

Most of the time we have to implement live search using ajax to lookup user directory or employee search. Today we are going to implement Jquery ajax live search. We are going to made Jquery ajax request after three characters and get the response in the form of json object and display the response content dynamically.

Create Database table

Create “trn_employee” table in mysql database using below sql table script and insert below records.

DROP TABLE IF EXISTS `technicalkeeda`.`trn_employee`;
CREATE TABLE  `technicalkeeda`.`trn_employee` (
  `employee_id` bigint(20) NOT NULL auto_increment,
  `first_name` varchar(255) collate latin1_general_ci default NULL,
  `last_name` varchar(255) collate latin1_general_ci default NULL,
  PRIMARY KEY  (`employee_id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
 
INSERT INTO `trn_employee` (`employee_id`,`first_name`,`last_name`) VALUES 
 (1,'Yashwant','Chavan'),
 (2,'Dinesh','Chavan'),
 (3,'Abhijit','Chavan'),
 (4,'Rahul','Patil'),
 (5,'Sujit','Patil'),
 (6,'Kapil','Ghate');

Codeigniter Controller(Employee.php)

Create Employee Controller class having default index() method which made request to EmployeeModel and get the Employee result base on search query. Employee list result is converted into json object format.

<?php
class Employee extends Controller {

 function Employee(){
  parent::Controller();
  $this->load->model('EmployeeModel');
 }

 public function index(){
  $search=  $this->input->post('search');
  $query = $this->EmployeeModel->getEmployee($search);
  echo json_encode ($query);
 }
}
?>

Model Class (EmployeeModel.php File)

Define Model class contains getEmployee() method which return employee.

<?php
class EmployeeModel extends Model {

 function EmployeeModel(){
  parent::Model(); 
 }

 function getEmployee($search){
  $this->db->select("EMPLOYEE_ID,FIRST_NAME,LAST_NAME");
  $whereCondition = array('LAST_NAME' =>$search);
  $this->db->where($whereCondition);
  $this->db->from('trn_employee');
  $query = $this->db->get();
  return $query->result();
 }
?>

Json Response

echo json_encode ($query); converts the resultant employee list into json object format.

[
{"EMPLOYEE_ID":"1","FIRST_NAME":"Yashwant","LAST_NAME":"Chavan"},
{"EMPLOYEE_ID":"2","FIRST_NAME":"Dinesh","LAST_NAME":"Chavan"},
{"EMPLOYEE_ID":"3","FIRST_NAME":"Abhijit","LAST_NAME":"Chavan"}
]

index.php

Capture the keyup() event and made the Jquery ajax request to Employee Controller. Jquery ajax request is made after 3 characters. And get the json response and display the employee list.

<html>
<head>
<style>
#search {
 background-color: lightyellow;
 outline: medium none;
 padding: 8px;
 width: 300px;
 border-radius: 2px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
 border-radius: 3px;
 border: 2px solid orange;
}

ul {
 width: 300px;
 margin: 0px;
 padding-left: 0px;
}

ul li {
 list-style: none;
 background-color: lightgray;
 margin: 1px;
 padding: 1px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
 border-radius: 3px;
}
</style>

<script type="text/javascript" language="javascript" src="http://www.technicalkeeda.com/js/javascripts/plugin/jquery.js"></script>
<script type="text/javascript" src="http://www.technicalkeeda.com/js/javascripts/plugin/json2.js"></script>
<script>
 $(document).ready(function(){
   $("#search").keyup(function(){
  if($("#search").val().length>3){
  $.ajax({
   type: "post",
   url: "http://localhost/technicalkeeda/index.php/employee",
   cache: false,    
   data:'search='+$("#search").val(),
   success: function(response){
    $('#finalResult').html("");
    var obj = JSON.parse(response);
    if(obj.length>0){
     try{
      var items=[];  
      $.each(obj, function(i,val){           
          items.push($('<li/>').text(val.FIRST_NAME + " " + val.LAST_NAME));
      }); 
      $('#finalResult').append.apply($('#finalResult'), items);
     }catch(e) {  
      alert('Exception while request..');
     }  
    }else{
     $('#finalResult').html($('<li/>').text("No Data Found"));  
    }  
    
   },
   error: function(){      
    alert('Error while request..');
   }
  });
  }
  return false;
   });
 });
</script>
</head>
<body>
<div id="container">
<p>Note:- Please start typing surname as "Chavan", "Patil"</p>
<input type="text" name="search" id="search" />
<ul id="finalResult"></ul>
</div>
</body>
</html>
(Visited 56 times, 1 visits today)

Comments

comments

Leave a Reply