In this article, we will explain to you how to create an ajax autocomplete search using select2 in CodeIgniter 4(Codeigniter 4 Select2 Ajax Autocomplete Search Example). We can easily make an ajax Autocomplete search using select2 in CodeIgniter 4 application.

In this example, we use the seclect2 js library for autocomplete search from the database in Codeigniter 4.  so you can see our following example.
Overview
Step 1: Download Codeigniter
Step 2: Basic Configurations
Step 3: Create a Database in table
Step 4: Connect to Database
Step 5: Create Controller and Model
Step 6: Create Views Files
Step 7: Run The Application

Step 1: Download Codeigniter
If you want to download or install the latest version of CodeIgniter 4 then you can go to Codeigniter’s official site and download the latest version of Codeigniter 4. after the downloaded you can configure in “xampp/htdocs/” directory.

Step 2: Basic Configurations
If you want to Basic Configurations in your project then you can below Url.
Codeigniter 4 Removing Index.Php From Url

Step 3: Create a Database in table
In this step, We will create the database and table.

CREATE TABLE IF NOT EXISTS `students` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(64) NOT NULL,
  `last_name` varchar(64) NOT NULL,
  `address` text NOT NULL,
  `email` varchar(64) NOT NULL,
  `mobile` varchar(12) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

INSERT INTO `students` (`id`, `first_name`, `last_name`, `address`, `email`, `mobile`) VALUES
(1, 'john', 'doe', 'USA', '[email protected]', '787878787'),
(2, 'kal', 'mark', 'CANADA', '[email protected]', '7887878787'),
(3, 'James', 'Mary', 'USA', '[email protected]', '4364373434'),
(4, 'William', 'Elizabeth', 'USA', '[email protected]', '7878787'),
(5, 'Matthew', 'Betty', 'USA', '[email protected]', '898989'),
(6, 'Anthony', 'Margaret', 'INDIA', '[email protected]', '8989898989'),
(7, 'Donald', 'Ashley', 'CANADA', '[email protected]', '3343434345'),
(8, 'Kevin', 'Carol', 'USA', '[email protected]', '2223334445');

Step 4: Connect to Database
Go to the “app/Config/Database.php” folder and open the database.php file some changes in this file like hostname, database username, database password, and database name.

	public $default = [
		'DSN'      => '',
		'hostname' => 'localhost',
		'username' => 'root',
		'password' => '',
		'database' => 'codeigniter4_pagination',
		'DBDriver' => 'MySQLi',
		'DBPrefix' => '',
		'pConnect' => false,
		'DBDebug'  => (ENVIRONMENT !== 'production'),
		'cacheOn'  => false,
		'cacheDir' => '',
		'charset'  => 'utf8',
		'DBCollat' => 'utf8_general_ci',
		'swapPre'  => '',
		'encrypt'  => false,
		'compress' => false,
		'strictOn' => false,
		'failover' => [],
		'port'     => 3306,
	];

Step 5: Create Controller and Model
In this step, we will create the “Student.php” controller and the “StudentModel.php” model.
app/Controllers/Student.php

<?php 

namespace App\Controllers;
 
use CodeIgniter\Controller;
use App\Models\StudentModel;
 
class Student extends Controller
{
 
	public function __construct()
    {
         helper(['form', 'url']);
    }
    public function index()
    {   
        return view('list');
    }
	
    function ajaxSearch(){
       	$model = new StudentModel();
			
        $query=$model->like('first_name',$_REQUEST['q'])
          ->select('id, first_name as text')
          ->limit(10)->get();
	$data_result = $query->getResult();		
        echo json_encode($data_result);
    }  
 
}

?>

app/Models/StudentModel.php

<?php 
namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
 
class StudentModel extends Model
{
    protected $table = 'Students';
 
    protected $allowedFields = ['first_name','last_name','address','email', 'mobile'];
}
?>

Step 6: Create Views Files
Finally, we will create the list.php in the app/views directory.

app/views/list.php

<!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 Select2 Ajax Autocomplete Search Example - XpertPhp</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/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
</head>
<body>
  <div class="container mt-5">
    <select class="search form-control" name="search"></select>
  </div>
</body>
<script>
      $('.search').select2({
        placeholder: '--- Search Student ---',
        ajax: {
          url: '<?php echo site_url(); ?>student/ajaxSearch',
          dataType: 'json',
          delay: 250,
          processResults: function(data){
            return {
              results: data
            };
          },
          cache: true
        }
      });
</script>

</html>

Step 7: Run The Application
We can start the server and run the codeigniter 4 application using the below command.

php spark serve

Now we will run our example using the below Url in the browser.

http://localhost:8080/student

If you liked this article, you can also download it through our Github Repository.