CodeIgniter Autocomplete Search from Database using AJAX Example

Hi! In this post, let's see how to autocomplete search from database using codeigniter and ajax. We are going to pull in live search thing something similar to Google search. As soon as you start typing in the textbox, the related suggestions will appear from the database. To implement this auto complete feature we need a jquery plugin called 'Select2'.

Select2 is an excellent plug-in that supercharges the regular select box with search functionality. It's really inappropriate to make the end user to skim through hundreds of options to pick just one. With Select2 the entire process is a breeze. It adds up a search filter to the dropdown (select box), thus populating results on fly with the help of ajax.

codeigniter autocomplete search from database ajax

AJAX Autocomplete Search from Database in CodeIgniter:

To implement the live autocomplete search in codeigniter, we need two JavaScript libraries, 1. jquery.js and 2. select2.js. Either download them or use from the cdn library just like I do in this demo.

Just follow the below steps and you'll be good.

Step-1) Create Database

For database, I'm going to use MySQL here. Create a dummy database, a table and some records to use in the example. Below is a sql file. Run the queries on mysql and it will take care of database creation.

CREATE `db_demo`;
USE `db_demo`;
CREATE TABLE IF NOT EXISTS `tbl_language` (
  `id` int(9) NOT NULL AUTO_INCREMENT,
  `lname` varchar(50) NOT NULL,
  `lcode` varchar(2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6;

INSERT INTO `tbl_language` (`id`, `lname`, `lcode`) VALUES
(1, 'English', 'en'),
(2, 'Afrikaans', 'af'),
(3, 'Greek', 'el'),
(4, 'Finnish', 'fi'),
(5, 'Spanish', 'es');

Step-2) Create Model

We need a codeigniter model to handle the database transactions. So create a model file inside 'application' > 'models' folder. It contains the function getLanguage() to fetch language names from the database that match the search term entered by the user.

SearchModel.php

<?php
class SearchModel extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }
    
    function getLanguage($str)
    {
        $this->db->select('id, lname as text');
        $this->db->like('lname', $str);
        $query = $this->db->get('tbl_language');
        return $query->result();
    }
}
?>

Step-3) Create Controller

Next create a controller file inside 'application' > 'controllers' folder. It contains two functions,

  1. index() - this is the default method that just loads the view file.
  2. search() - This function will be triggered during the ajax call. It receives the incoming search term ('q'), communicate with the model and get the results matching the search term, encode them to json and pass it back to the browser.

SearchController.php

<?php
class SearchController extends CI_Controller {
    function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->database();
    }

    function index()
    {
        $this->load->view('SearchView');
    }
    
    function search()
    {
        $q = $this->input->get('q');
        $this->load->model('SearchModel');
        echo json_encode($this->SearchModel->getLanguage($q));
    }
}
?>

Step-4) Create View

This is the final step. Create a view file inside 'application' > 'views' folder. It contains all the front-end logic, including html markup, css and java script. Here is where we need to fire the ajax call. Just load the js libraries and bind the select2() method to the dropdown that requires auto complete feature.

SearchView.php

<!DOCTYPE html>
<html>
<head>
    <title>CodeIgniter Search from Database 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</h3>
    <select id="language" name="language" class="itemName form-control" style="width:300px" ></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">
    $('#language').select2({
        placeholder: '-Select Language-',
        minimumInputLength: 1,
        ajax: {
            url: "<?php echo base_url();?>index.php/SearchController/search",
            dataType: 'json',
            delay: 250,
            processResults: function (data) {
                return {
                    results: data
                };
            },
            cache: true
        }
    });
    </script>
</body>
</html>

That's it! We have everything in place. It's time to test the search filter. Just run the controller and if everything is okay, you'll see a drop-down box. Start typing in the textbox and you will see the suggestions popping up below in a list.

ajax autocomplete search select2

With the plug-in, you can not only pull in the results from the database, but from other sources such as a remote REST API or just a local JS array.

Read Also:

That explains about implementing search from database in codeigniter and ajax. Most modern web apps uses autocomplete search and is a sure fire way to increase user experience. Every little detail counts! So make sure you implement it on your next project. I hope this tutorial is useful for you. Please share it on your social circle if you like it.

3 comments:

  1. cannot select list data dude

    ReplyDelete
  2. Ajax Search http://vintageitsolutions.com

    ReplyDelete
  3. Thank you for the useful code.Would you please like to upload the variant of this code "bringing images against languages names.."

    ReplyDelete