jQuery UI Autocomplete is a great choice to take into consideration if you want to improve the search functionality of your CodeIgniter 4 application. Based on the user’s input in a textbox, you can use display a list of recommendations.
jQuery UI Autocomplete provides the flexibility to display suggestions with or without AJAX, depending on your specific needs.
In this tutorial, we will explore how to implement jQuery UI Autocomplete in a CodeIgniter 4 project and load data from a MySQL database using jQuery AJAX. By the end of this tutorial, you will have a better understanding of how to incorporate this useful search functionality into your own CodeIgniter 4 application.
I am using CSRF token with an AJAX request, if you don’t know how to enable it then you can view this tutorial.

Contents
- Create Table
- Add jQuery UI
- Create Model
- Create Route for Autocomplete Request
- Create a Controller and Method for Autocomplete
- Create a View for Autocomplete
- Demo
- Conclusion
1. Create Table
- Create a new table
usersusing migration.
php spark migrate:create create_users_table
- Now, navigate to
app/Database/Migrations/folder from the project root. - Find a PHP file that ends with
create_users_tableand open it. - Define the table structure in the
up()method. - Using the
down()method deleteuserstable which calls when undoing migration.
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateUsersTable extends Migration
{
public function up() {
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 5,
'unsigned' => true,
'auto_increment' => true,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '100',
],
'email' => [
'type' => 'VARCHAR',
'constraint' => '100',
],
'city' => [
'type' => 'VARCHAR',
'constraint' => '100',
],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('users');
}
//--------------------------------------------------------------------
public function down() {
$this->forge->dropTable('users');
}
}
- Run the migration –
php spark migrate
2. Add jQuery UI
Before using jQuery UI Autocomplete in your CodeIgniter 4 application, the jQuery UI library must be added. To do this, either download the necessary files from the jQuery UI website and add them to your public/ folder or use CDN.
You can then start setting up your application’s autocomplete feature once that is finished.
<!-- Script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <!-- jQuery UI --> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
3. Create Model
- Create
UsersModel –
php spark make:model Users
- Open
app/Models/Users.phpfile. - In
$allowedFieldsArray specify field names –['name','email','city'].
Completed Code
<?php
namespace App\Models;
use CodeIgniter\Model;
class Users extends Model
{
protected $DBGroup = 'default';
protected $table = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $insertID = 0;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $protectFields = true;
protected $allowedFields = ['name', 'email','city'];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
// Validation
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = [];
protected $afterInsert = [];
protected $beforeUpdate = [];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
}
4. Create Route for Autocomplete Request
- Open
app/Config/Routes.phpfile. - Define 2 routes –
- /
- users/getUsers – It is used to load autocomplete data.
Completed Code
$routes->get('/', 'UsersController::index');
$routes->post('users/getUsers', 'UsersController::getUsers');
5. Create a Controller and Method for Autocomplete
Create a controller and method that will handle the autocomplete functionality.
- Create
UsersControllerController –
php spark make:controller UsersController
- Open
app/Controllers/UsersController.phpfile. - Import
UsersModel. - Create 2 methods –
- index() – Load
indexview. - getUsers() – This method is use to handle jQuery UI autocomplete AJAX requests.
- index() – Load
Capture the POST values and store them in the $postData variable. Then, initialize the $response array to hold the response data, including a newly generated CSRF token stored in $response['token'].
If the search is submitted via POST method, retrieve the value from $postData['search'] and use it to search the users table by matching against the name field.
Iterate through the fetched records and create a new array called $data. Each element of $data should have two keys, ‘value’ and ‘label’. Assign the value of $user['id'] to the ‘value’ key and the value of $user['name'] to the ‘label’ key.
Assign $data Array to $response['data'].
Finally, convert the $response array to JSON format and return it.
Completed Code
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\Users;
class UsersController extends BaseController
{
public function index(){
return view('index');
}
public function getUsers(){
$request = service('request');
$postData = $request->getPost();
$response = array();
// Read new token and assign in $response['token']
$response['token'] = csrf_hash();
$data = array();
if(isset($postData['search'])){
$search = $postData['search'];
// Fetch record
$users = new Users();
$userlist = $users->select('id,name')
->like('name',$search)
->orderBy('name')
->findAll(5);
foreach($userlist as $user){
$data[] = array(
"value" => $user['id'],
"label" => $user['name'],
);
}
}
$response['data'] = $data;
return $this->response->setJSON($response);
}
}
6. Create a View for Autocomplete
After setting up the controller and method for handling the autocomplete functionality, the next step is to create a view that will display the autocomplete widget.
Create index.php file in app/Views/.
Add a hidden element to store CSRF token.
<input type="hidden" class="txt_csrfname" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>" />
Create 2 text elements. The first text element is used to initialize autocomplete and the second element is used to store selected suggestion item value.
Script –
Initialize autocomplete on the #autocompleteuser element, use the .autocomplete() function and set the ‘source’ option to load data.
Retrieve the CSRF token name and hash from the hidden input field and assign them to the ‘csrfName’ and ‘csrfHash’ variables.
Then, send an AJAX request to <?=site_url('users/getUsers')?>. Use the ‘post’ method, set the ‘dataType’ to ‘json’, and pass the typed value and CSRF token as data.
In the successful callback, update the CSRF token value by setting the value of the hidden input element with $('.txt_csrfname').val(data.token). Then pass the data.data to the response() function.
Finally, with the select event, get the selected suggestion label and value using ui.item.label and ui.item.value. Then, update the #autocompleteuser selector with ui.item.label and update the #userid selector with ui.item.value.
Completed Code
<!doctype html>
<html>
<head>
<title>How to Implement jQuery UI Autocomplete in CodeIgniter 4</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- jQuery UI CSS -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/themes/smoothness/jquery-ui.css">
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<!-- jQuery UI JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
</head>
<body>
<!-- CSRF token -->
<input type="hidden" class="txt_csrfname" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>" />
<!-- Autocomplete -->
Search User : <input type="text" id="autocompleteuser">
<br><br>
Selected user id : <input type="text" id="userid" value='0' >
<!-- Script -->
<script type='text/javascript'>
$(document).ready(function(){
// Initialize
$( "#autocompleteuser" ).autocomplete({
source: function( request, response ) {
// CSRF Hash
var csrfName = $('.txt_csrfname').attr('name'); // CSRF Token name
var csrfHash = $('.txt_csrfname').val(); // CSRF hash
// Fetch data
$.ajax({
url: "<?=site_url('users/getUsers')?>",
type: 'post',
dataType: "json",
data: {
search: request.term,
[csrfName]: csrfHash // CSRF Token
},
success: function( data ) {
// Update CSRF Token
$('.txt_csrfname').val(data.token);
response( data.data );
}
});
},
select: function (event, ui) {
// Set selection
$('#autocompleteuser').val(ui.item.label); // display the selected text
$('#userid').val(ui.item.value); // save selected id to input
return false;
},
focus: function(event, ui){
$( "#autocompleteuser" ).val( ui.item.label );
$( "#userid" ).val( ui.item.value );
return false;
},
});
});
</script>
</body>
</html>
7. Demo
8. Conclusion
Congratulations! Your CodeIgniter 4 application now uses jQuery UI Autocomplete with success. You discovered how to extract information from a MySQL database and present it in an autocomplete list, giving users a simple and effective way to search and choose values.
In addition, you learned how to include a CSRF token to AJAX requests to defend your application against cross-site request forgery attacks. This vital security measure guarantees that your application is secure and safeguarded against malicious attacks.
The autocomplete data returned by the controller should contain keys ‘value’ and ‘label’. To suit your needs, you can modify the LIMIT.
If you found this tutorial helpful then don't forget to share.NOTE – If the CSRF token is not enabled in your project then remove the CSRF token code from the controller and view.