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 DATABASE demo;

Create a table users, and propel following data within.

CREATE TABLE users (
    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.

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

# XAMPP
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.

<?php
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')
                    ->limit(10)->get();
        $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.

app/Config/Routes.php
$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">
<head>
    <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 - Mywebtuts.com</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
    <style>
        .container {
            max-width: 500px;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <select class="search form-control" name="search"></select>
    </div>
</body>
<script>

    /*------------------------------------------
    --------------------------------------------
    Autocomplete Search
    --------------------------------------------
    --------------------------------------------*/
    $('.search').select2({
        placeholder: '--- Search User ---',
        ajax: {
            url: '<?php echo base_url('AutocompleteSearch/ajaxSearch');?>',
            dataType: 'json',
            delay: 250,
            processResults: function(data){
                return {
                    results: data
                };
            },
            cache: true
        }
    });
</script>
</html>
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:

http://localhost:8080/

I hope it will help you...

#Codeigniter 4