Hi friends! In this post, today we will create an autocomplete search box from the database using Codeigniter and ajax. We are going to create in live search thing something similar to Google search. When you start typing in the textbox, the related suggestions will show from the database. To implement this auto-complete search feature we need a jquery plugin called 'Select2'.

Select2 is an excellent JQuery plug-in that converts the regular select box with search functionality. It's really inappropriate to make the end-user skim through hundreds of options to pick just one. It added up a search filter feature to the dropdown (select box), this is populating results with the help of ajax.

Just follow the below steps to create a live search from the database.

Step 1. Creating a Database

For the database, I'm using MySQL here. Now create a dummy database named live_search, and a table, and some dummy records to use in the example. Below is a SQL file. Run those queries on MySQL and it will create a database for you.

CREATE `live_search`;
USE `live_search`;
CREATE TABLE IF NOT EXISTS `tbl_country` (
  `id` int(9) NOT NULL AUTO_INCREMENT,
  `country_name` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6;

INSERT INTO `tbl_country` (`id`, `country_name`) VALUES
(1, 'India'),
(2, 'United States'),
(3, 'United Kingdom'),
(4, 'Australia'),
(5, 'New Zealand'),
(6, 'Singapore'),
(7, 'Japan'),
(8, 'Spain'),
(9, 'Canada'),
(10, 'France');

Step 2. Creating a Model File SearchCountryModel.php

Now we need a Codeigniter model to handle all the database actions. To create a model file inside 'application' => 'models' folder. It contains the function getCountry() to fetch Country names from the database that match the search term entered by the user in the search textbox.

<?php
class SearchCountryModel extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }
    
    function getCountry($str)
    {
        $this->db->select('id, country_name as name');
        $this->db->like('country_name', $str);
        $query = $this->db->get('tbl_country');
        return $query->result();
    }
}
?>

Step 3. Creating a Controller File SearchCountry.php

The Next Step is to create a controller file inside the 'application' => 'controllers' folder. It contains two functions,
  1. index() -  Index is the default method that simply loads the view file.
  2. search() - The Search function will be triggered from the ajax call. It receives the incoming search term values ('q'), communicate with the model and get the results matching with the search term, encodes them to JSON, and passes it back to the browser.

<?php
class SearchCountry extends CI_Controller {
    function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->database();
    }
    function index()
    {
        $this->load->view('SearchCountryView');
    }
    
    function search()
    {
        $q = $this->input->get('q');
        $this->load->model('SearchCountryModel');
        echo json_encode($this->SearchCountryModel->getCountry($q));
    }
}
?>

Step 4. Creating a Controller File SearchCountry.php

At last, This is the final step of ours tutorial. Now We Create a view file inside the 'application' => 'views' folder. It contains all the front-end Form And logic, including HTML markup, CSS, and javascript code. Here we need to fire the ajax call. Just load the javascript libraries and bind the select2() method to the dropdown that requires an auto-complete feature.


<!DOCTYPE html>
<html>
<head>
    <title>CodeIgniter Live Search from Database With Example</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <h3>CodeIgniter Autocomplete Demo From Database With Example</h3>
    <select id="country" name="country" class="itemName form-control" style="width:400px" ></select>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
    
    <script type="text/javascript">
    $('#country').select2({
        placeholder: '-Select Country-',
        minimumInputLength: 1,
        ajax: {
            url: "<?php echo base_url();?>index.php/SearchCountry/search",
            dataType: 'json',
            delay: 250,
            processResults: function (data) {
                return {
                    results: data
                };
            },
            cache: true
        }
    });
    </script>
</body>
</html>


Create an autocomplete search box from the database using Codeigniter and ajax | MadeCodingEasy