Codeigniter 4 - Select2 AJAX Autocomplete Search from Database Tutorial

Apr 20, 2022 . Admin

Hi Dev,

In this quick example, let's see Codeigniter 4 select2 ajax autocomplete search from database example. In this article, we will implement a Codeigniter 4 select2 ajax autocomplete search from the database. This post will give you a simple example of the Codeigniter 4 select2 ajax autocomplete search. This article goes into detail on the example CodeIgniter 4 select2 ajax autocomplete search.

This post is focused on Select2 an ideal jQuery plugin. I explained simply about which gives freedom of customization to a standard select box. This post will give you a simple example of With it. if you want to see an example of you can spruce up a search select box then you are the right place.

We would like to shed a little light on Autocomplete as well. It is also known as word completion. is a powerful feature, mainly found in web and mobile applications. It predicts the rest of the word when the user starts typing the word. The predicted word can be chosen by pressing on the tab key.

Step 1: Install Codeigniter 4

This is optional; however, if you have not created the codeigniter app, then you may go ahead and execute the below command:

composer create-project codeigniter4/appstarter ci-news

As soon as the project is downloaded, change the name of the appstarter folder to something like this codeigniter-select. after,go inside the app folder.

cd codeigniter-select

This is the more simpler method then above, straight download the Codeigniter application.

Step:2 Enable Error Reporting

Here this step,Error reporting is essential for debugging the application. It protects from the errors that occurred from the recklessness.

Go to app/Config/Boot/development.php and change the display_errors value to 1 rather then 0.

Repeat the same process in app/Config/Boot/production.php.

ini_set('display_errors', '1');
Step:3 Create Database and Table

In this step here we will keep the data that we will be showing using AJAX request through select2 autocomplete search.

Go to PHPMyAdmin and create a new database. If you already have database and table setup then skip this step.


Create a table users, and propel following data within.

    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
INSERT INTO `users` (`id`, `name`) VALUES
(1, 'John Doe'),
(2, 'Vanya'),
(3, 'Luther'),
(4, 'Diego'),
(5, 'Klaus'),
(6, 'Ben'),
(7, 'Handler'),
(8, 'Dexter'),
(9, 'Mask'),
(10, 'Aladin');
Step:4 Make Database Connection

Now this step,I will Add database configurations like database name, username, password in application/config/database.php.

public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'test',
    'password' => '4Mu99BhzK8dr4vF1',
    'database' => 'demo',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'development'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,
CodeIgniter\Database\Exceptions\DatabaseException #8 Unable to connect database : Codeigniter

If anyhow you get the Codeigniter – cannot connect to MySQL database error, then change the hostname value based on your local server e.g MAMPP or XAMPP.

public $default = [
     'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',

public $default = [
     'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',
Step:5 Create Controller

In this step,I will Create a new controller in app/Controllers/AutocompleteSearch.php. The code here in this file will be solely responsible for fetching the data from the database on AJAX request made from Select2 dropdown.

namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;

class AutocompleteSearch extends Controller

     * Write code on Method
     * @return response()
    public function index() {
        return view('home');
     * Write code on Method
     * @return response()
    public function ajaxSearch()
        helper(['form', 'url']);

        $data = [];

        $db      = \Config\Database::connect();
        $builder = $db->table('users');   

        $query = $builder->like('name', $this->request->getVar('q'))
                    ->select('id, name as text')
        $data = $query->getResult();
        echo json_encode($data);

Step:6 Create Route

So, in this step create a route to show the AJAX autocomplete search element. Open the app/Config/Routes.php and incorporate the following code.

$routes->get('/', 'AutocompleteSearch::index');
Step:7 Implement AJAX Autocomplete Search in Codeigniter View

Now this srep, I will reached the last step of this tutorial. I am using Bootstrap to design the Select Dropdown HTML element; you can avoid it if you want.

Add Select2 JavaScript and CSS file on top using CDN links. As you can see, we did the same thing.

Create app/Views/home.php file and place the following code.
<!doctype html>
<html lang="en">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Upload Multiple Files or Images in Codeigniter 4 -</title>
    <link rel="stylesheet" href="">
    <script src=""></script>
    <link href="" rel="stylesheet" />
    <script src=""></script>
        .container {
            max-width: 500px;
    <div class="container mt-5">
        <select class="search form-control" name="search"></select>

    Autocomplete Search
        placeholder: '--- Search User ---',
        ajax: {
            url: '<?php echo base_url('AutocompleteSearch/ajaxSearch');?>',
            dataType: 'json',
            delay: 250,
            processResults: function(data){
                return {
                    results: data
            cache: true
Step 8 : Run Codeigniter App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:

php spark serve

Now, Go to your web browser, type the given URL and view the app output:


I hope it will help you...

#Codeigniter 4