Monday 23 July 2018

Autocomplete Search Box using Typeahead in Codeigniter



In this post We are going to discuss how to make autocomplete or auto search or auto suggest textbox in Codeigniter application by using Typeahead.js bootstrap jquery plugin. By using Typeahead.js plugin with Codeigniter framework we will make dynamic real time auto suggest search box with not only display text suggestion data but also it will also display images with auto suggest search. In most of the tutorial you can find simple how to use typeahead.js with Codeigniter framework and it will only describe autocomplete search records below textbox, but in this tutorial we have also add one more feature like how to load images in Autocomplete search with custom html template using typeahead.js plugin. So when we have type something in textbox then it will not only autocomplete search but also it will also load images with autocomplete search also using typeahead.js with codeigniter.

We all know Codeigniter is a MVC framework which has build using PHP and it is very famouse and widely use this framework for development of web application. So, in web application we have to provide one feature like search box, so user can search into system any required data. For in search if you user has start type his query and he has get all possible result of his query in auto suggest search drop down textbox then he can easily get result without type whole word. So this type of functionality we have to build here in our codeigniter application. For this we have using Typeahead.js library which is flexible javascript library and it has provide us strong foundation for auto suggest or autocomplete search. For if you want to make dynamic real time autocomplete feature which search data into mysql database and fetch that data and display into autocomplete search result in real time for this we have to use typeahead.js library which has provide great autocomplete search functionality with stylish UI also and we can easily customize also.






Step 1: Create Table


This is first step and in this we have to create one table and in this table we have insert some dummy data. For this we have make one "tbl_student" table and inserted some records which you can find below.

tbl_student table

--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_student`
--

CREATE TABLE `tbl_student` (
  `student_id` int(11) NOT NULL,
  `student_name` varchar(250) NOT NULL,
  `student_phone` varchar(20) NOT NULL,
  `image` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_student`
--

INSERT INTO `tbl_student` (`student_id`, `student_name`, `student_phone`, `image`) VALUES
(1, 'Pauline S. Rich', '412-735-0224', 'image_1.jpg'),
(2, 'Sarah C. White', '320-552-9961', 'image_2.jpg'),
(3, 'Samuel L. Leslie', '201-324-8264', 'image_3.jpg'),
(4, 'Norma R. Manly', '478-322-4715', 'image_4.jpg'),
(5, 'Kimberly R. Castro', '479-966-6788', 'image_5.jpg'),
(6, 'Elaine R. Davis', '701-685-8912', 'image_6.jpg'),
(7, 'Concepcion S. Gardner', '607-829-8758', 'image_7.jpg'),
(8, 'Patricia J. White', '803-789-0429', 'image_8.jpg'),
(9, 'Michael M. Bothwell', '214-585-0737', 'image_9.jpg'),
(10, 'Ronald C. Vansickle', '630-571-4107', 'image_10.jpg'),
(11, 'Clarence A. Rich', '904-459-3747', 'image_11.jpg'),
(12, 'Elizabeth W. Peterson', '404-380-9481', 'image_12.jpg'),
(13, 'Renee R. Hewitt', '323-350-4973', 'image_13.jpg'),
(14, 'John K. Love', '337-229-1983', 'image_14.jpg'),
(15, 'Teresa J. Rincon', '216-394-6894', 'image_15.jpg'),
(16, 'Erin S. Huckaby', '503-284-8652', 'image_16.jpg'),
(17, 'Brian A. Handley', '989-304-7122', 'image_17.jpg'),
(18, 'Michelle A. Polk', '540-232-0351', 'image_18.jpg'),
(19, 'Wanda M. Brown', '718-262-7466', 'image_19.jpg'),
(20, 'Phillip A. Hatcher', '407-492-5727', 'image_20.jpg'),
(21, 'Dennis J. Terrell', '903-863-5810', 'image_21.jpg'),
(22, 'Britney F. Johnson', '972-421-6933', 'image_22.jpg'),
(23, 'Rachelle J. Martin', '920-397-4224', 'image_23.jpg'),
(24, 'Leila E. Ledoux', '615-425-9930', 'image_24.jpg'),
(25, 'Darrell A. Fields', '708-887-1913', 'image_25.jpg'),
(26, 'Linda D. Carter', '909-386-7998', 'image_26.jpg'),
(27, 'Melva J. Palmisano', '630-643-8763', 'image_27.jpg'),
(28, 'Jessica V. Windham', '513-807-9224', 'image_28.jpg'),
(29, 'Karen T. Martin', '847-385-1621', 'image_29.jpg'),
(30, 'Jack K. McDonough', '561-641-4509', 'image_30.jpg'),
(31, 'John M. Williams', '508-269-9346', 'image_31.jpg'),
(32, 'Amelia W. Davis', '347-537-8052', 'image_32.jpg'),
(33, 'Gertrude W. Lawrence', '510-702-7415', 'image_33.jpg'),
(34, 'Michael L. Harris', '252-219-4076', 'image_34.jpg'),
(35, 'Casey A. Groves', '810-334-9674', 'image_35.jpg'),
(36, 'James H. Wilson', '865-259-6772', 'image_36.jpg'),
(37, 'James A. Wesley', '443-217-1859', 'image_37.jpg'),
(38, 'Armando C. Gay', '716-252-9230', 'image_38.jpg'),
(39, 'James M. Duarte', '402-840-0541', 'image_39.jpg'),
(40, 'Jason E. West', '360-610-7730', 'image_40.jpg'),
(41, 'Gloria H. Saucedo', '205-861-3306', 'image_41.jpg'),
(42, 'Paul T. Moody', '914-683-4994', 'image_42.jpg'),
(43, 'Sandra L. Williams', '310-335-1336', 'image_43.jpg'),
(44, 'Elaine T. Deville', '626-513-8306', 'image_44.jpg'),
(45, 'Robyn L. Spangler', '754-224-7023', 'image_45.jpg'),
(46, 'Sam A. Pino', '806-823-5344', 'image_46.jpg'),
(47, 'Joseph H. Marble', '201-917-2804', 'image_47.jpg'),
(48, 'Mark M. Bassett', '206-592-4665', 'image_48.jpg'),
(49, 'Edgar M. Billy', '978-365-0324', 'image_49.jpg'),
(50, 'Connie M. Yang', '815-288-5435', 'image_50.jpg');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_student`
--
ALTER TABLE `tbl_student`
  ADD PRIMARY KEY (`student_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_student`
--
ALTER TABLE `tbl_student`
  MODIFY `student_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=51;








Step 2: Make Database Connection in Codeigniter


Now we have to make database connection by defining required information like hostname, database name, username and password. By this credential we can make database connection in codeigniter.

application/config/database.php



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

$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: Create Controller


After making of database connection in Codeigniter Application then we have to make controller for handle http request. So, here we have make Autocomplete Controller in application/controllers folder. This controller will received user request and it will send request to model and from model it will received data which it will send to view file. Here index() method will load root of this controller and fetch() will received ajax request for fetch data.

application/controllers/Autocomplete.php



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

class Autocomplete extends CI_Controller {
 
 function index()
 {
  $this->load->view('autocomplete_view') ;
 }
 function fetch()
 {
  $this->load->model('autocomplete_model');
  echo $this->autocomplete_model->fetch_data($this->uri->segment(3));
 }
}
?>


Step 4: Create Models


After Creating controllers we have to make models, in this model we can perform database side operation, so here we will write login for search data from mysql table, which we can found below.

application/models/Autocomplete_model.php



<?php
class Autocomplete_model extends CI_Model
{
 function fetch_data($query)
 {
  $this->db->like('student_name', $query);
  $query = $this->db->get('tbl_student');
  if($query->num_rows() > 0)
  {
   foreach($query->result_array() as $row)
   {
    $output[] = array(
     'name'  => $row["student_name"],
     'image'  => $row["image"]
    );
   }
   echo json_encode($output);
  }
 }
}

?>


Step 5: Create View


Lastly we have to create view file, which is an output file of our Codeigniter framework, last and final output has been display using this view file. In this file we can define css and javascript file details. Here we have imported required library of Typeahead.js library required file. Below we can find complete source code of this file.

application/views/autocomplete_view.php



<html>
<head>
    <title>Autocomplete Search Box using Typeahead 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>
 <link rel="stylesheet" href="https://twitter.github.io/typeahead.js/css/examples.css" /> 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
 <script src="https://twitter.github.io/typeahead.js/js/handlebars.js"></script>
 <script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>

 <style>
 .box
 {
  width:100%;
  max-width: 650px;
  margin:0 auto;
 }
 </style>
</head>
<body>
 <div class="container">
  <br />
  <br />
  <h3 align="center">Autocomplete Search Box using Typeahead in Codeigniter</h3>
  <br />
  <div id="prefetch">
   <input type="text" name="search_box" id="search_box" class="form-control input-lg typeahead" placeholder="Search Here" />
  </div>
 </div>
</body>
</html>
<script>
$(document).ready(function(){
  var sample_data = new Bloodhound({
   datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
   queryTokenizer: Bloodhound.tokenizers.whitespace,
   prefetch:'<?php echo base_url(); ?>autocomplete/fetch',
   remote:{
    url:'<?php echo base_url(); ?>autocomplete/fetch/%QUERY',
    wildcard:'%QUERY'
   }
  });
  

  $('#prefetch .typeahead').typeahead(null, {
   name: 'sample_data',
   display: 'name',
   source:sample_data,
   limit:10,
   templates:{
    suggestion:Handlebars.compile('<div class="row"><div class="col-md-2" style="padding-right:5px; padding-left:5px;"><img src="student_image/{{image}}" class="img-thumbnail" width="48" /></div><div class="col-md-10" style="padding-right:5px; padding-left:5px;">{{name}}</div></div>')
   }
  });
});
</script>


So, this is complete step by step process for how to use Typeahead.js with Codeigniter framework and make autocomplete textbox in which we have load images with search result on webpage.

20 comments:

  1. hola tengo este error

    Fatal error: Class 'CI_Model' not found in C:\xampp2\htdocs\busqueda\Autocomplete_model.php on line 3

    ReplyDelete
    Replies
    1. your model class name should be always the same with the model file name as well as in controller.

      Delete
  2. please could teach about codeigniter restful API and how to generate SQRC code with codeigniter

    ReplyDelete
  3. suggestion:Handlebars.compile

    error shows.

    ReplyDelete
  4. on selecting the fetch data its not showing on input box.

    ReplyDelete
    Replies
    1. Same here, did you manage to resolve it?

      Delete
    2. hello guys you just have to configure config.php
      //$config['base_url'] = '';
      $root="http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']);

      $config['base_url'] = $root;

      Delete
  5. on selecting the fetch data its not showing on input box. Please provide updated source

    ReplyDelete
  6. Sir it works good, but i just wanna add a fuzzy search to it, any solution for that ?

    ReplyDelete
  7. Thank you webslessons but this did not work

    ReplyDelete
  8. Output are showing but very much slow. How can I fast typing to Output result

    ReplyDelete
  9. I'm having a problem with adding space on the item, I want to search

    for instance the items inside my database: alive gut alive Uri alive vision

    when I'm typing "alive" in my search box all of the items are showing on the suggestions. but when I added some space or continue the item I want to search "alive " or "alive gut" it not showing any suggestions.

    ReplyDelete
  10. I'm having a problem with adding space on the item, I want to search

    for instance the items inside my database: alive gut alive Uri alive vision

    when I'm typing "alive" in my search box all of the items are showing on the suggestions. but when I added some space or continue the item I want to search "alive " or "alive gut" it not showing any suggestions.

    ReplyDelete
  11. error : new Bloodhound(.. can you solve this problem?

    ReplyDelete