Codeigniter 4 Select2 Autocomplete Search from Database
Select2 is an ideal jQuery plugin, which gives freedom of customization to a standard select box. With it, you can spruce up a search select box, ajax autocomplete and it offers several but useful options. Such as. Searching, tagging, remote data sets, infinite scrolling, and many other highly used options.
Before we begin, I 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.
Codeigniter 4 Select2 Example
Why autocomplete with the select box is needed? Well, we have an answer for you. Think, when you have thousands or maybe millions of records stored in the database.
You have a task to fetch all the records and display to the user. It’s a seer loss of resources if you load entire data at once and that too for few records. That is where Select2.js comes to make the coherence for human-computer interaction. It let us use the select box, and load data using autocomplete and refrain form loading all the result at once.
Here, the assortment of every step is given below, and please take care.
Table of Contents
Download Codeigniter 4 App
Composer Package Manager is required for this step, with that you can download the new Codeigniter application with a single below command.
composer create-project codeigniter4/appstarter
As soon as the project is downloaded, change the name of the appstarter folder to something like this codeigniter-select.
Than, go inside the app folder:
cd codeigniter-select
This is the more simpler method then above, straight download the Codeigniter application.
Enable Error Reporting
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');
Create Database and Table
Create a database, 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');
Make Database Connection
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',
...
]
Make Controller
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
{
public function index() {
return view('home');
}
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);
}
}
Create Route
This step answers the question of how to 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');
Implement AJAX Autocomplete Search in Codeigniter View
Eventually, we have 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>Codeigniter 4 jQuery Autocomplete Text Search Example</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>
$('.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>
Test Application
In the end, we are left with only testing of this application. Let’s check out what we have built so far. So, execute the following command to start the application in the browser:
php spark serve
Test the app with the following URL:
http://localhost:8080
You can download the full code of Codeigniter AJAX Autocomplete tutorial from GitHub.