Codeigniter 4 Select2 AJAX Autocomplete Search from Database Example

20-Apr-2022

.

Admin

Codeigniter 4 Select2 AJAX Autocomplete Search from Database Example

Hi Guys,

Today,I will exmpalin you how to make select2 ajax autocomplete search from the database in Codeigniter.we wil show example of codeigniter 4 select2 ajax autocomplete search from database. you how to efficiently use, implement Select2 Autocomplete jQuery library in Codeigniter 4 application. This post enumerates all the essentials factors that help you create ajax autocomplete search that fetches data from the 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.

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 Download Codeigniter 4 App


In this example,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.

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 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');

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 Make 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

{

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);

}

}

Step:6 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');

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 - positronx.io</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>

Now I will 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

It will help...

#Codeigniter 4

#Codeigniter