Codeigniter 4 Tutorials
- Codeigniter 4
- Application Run
- Application Structure
- Configuration files
- Errors
- Controller
- View
- Model
- How to remove index.php from URL
- Route
- CodeIgniter URLs
- Helper
- Session
- Global Functions and Constants
- Logging Information in CI4
- Error Handling
- Signin / SignUp
- Login / Register
- CRUD
- Crud 1
- Form Validation
- Data Table
- Pagination
- File Upload
- Show Data Using Ajax
- Select2 AJAX Autocomplete Search
- Curl Post
- Rest API
- Weblink
Home » Codeigniter 4 »
How to use Select2 AJAX Autocomplete Search in Codeigniter 4?
Database Table
File name : index.php
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, 'Mahtab'),
(2, 'Habib'),
(3, 'Sara'),
(4, 'Arham'),
(5, 'Sana'),
(6, 'Mahira'),
(7, 'adiba'),
(8, 'Adyan'),
(9, 'simran'),
(10, 'sonam');
Controller
Create controller in app/Controllers/AutocompleteSearch.php
File name : AutocompleteSearch.php
<?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);
}
}
Route
File name : index.php
$routes->get('/', 'AutocompleteSearch::index');
view
File name : home.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 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>
File name : index.php