Codeigniter – Autocomplete Search using Typeahead

In this post , I will explain how to implement  dynamic autocomplete search using typeahead  in codeigniter application. we will take simple bootstrap text box and make it dynamic real time search using typeahead in codeigniter application.

Step 1: Create Table

In this step we have to create table with some dummy records. For this example i will create “cs_subject” table and insert some dummy records.

CREATE TABLE IF NOT EXISTS `cs_subject` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Step 2: Configure Database

In this step, we will configure database credentials like username, password and database name. So change database details in application/config/database.php file

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

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => 'root',
	'database' => 'demo',
	'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: Create Controller

In this step we will create controller named as Autocomplete with index and search functions. Index fucntion will be used to load view file and search function will be used to search result based on input key from database. So create new controller in application/controllers folder and put below code.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Autocomplete extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->database();
        $this->load->helper('url');
        $this->load->model('Db_Model');
    }    
    public function index(){
		$this->load->view('auto_search');
    }	
    public function search(){
     $data['retval'] = $this->Db_Model->search($this->input->get('query'));
        echo json_encode( $data['retval']);
    }
}
Step 3: Create Modal

In this step we will create modal named as Db_Modal with search function. So create new modal in application/modal folder and put below code .

<?php 
class Db_Model extends CI_Model{    
    public function search($key){         
      return $this->db->like('name', $key)->get("cs_subject")->result();       
    }
}
?>
Step 3: Create view

In last step we will create new view file auto_search.php on views folder So create new view file on application/views folder and put below code.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Codeigniter  - jquery ajax autocomplete search using typeahead example- phpforever.com</title>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>  
</head>
<body>

<div class="container">
  <h5>Codeigniter  - jquery ajax autocomplete search using typeahead example- phpforever.com</h5><br>
   <input class="typeahead form-control" type="text">
</div>
</body>
<script type="text/javascript">
    $('input.typeahead').typeahead({
        source:  function (query, process) {
        return $.get('<?php site_url()?>/index.php/Autocomplete/search', { query: query }, function (data) {
                console.log(data);
                data = $.parseJSON(data);
                map = {};
                objects = [];
                 $.each(data, function(i, object) {
                    map[object.name] = object;
                    objects.push(object.name);
                });
              return process(objects);                
            });
        }
    });
</script>
</html>
Exit mobile version