An Autocomplete textbox gives suggestions based on user input.
The user can select an option from the list.
This generally uses in the field where a user needs to select an item from the available data.
In this tutorial, I show how you can add autocomplete on a textbox element using jQuery UI in CodeIgniter.
Contents
1. Table structure
In this example, I am using users
table and added some records –
CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(60) NOT NULL, `fullname` varchar(70) NOT NULL, `password` varchar(60) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2. Configuration
Navigate to application/config/database.php
and define Database connection.
$db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', // Username 'password' => '', // Password 'database' => 'tutorial', // Database name 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE );
Default controller
Open application/config/routes.php
and edit default_controller
value to User
.
$route['default_controller'] = 'User';
Load Database
To access the MySQL database require loading database
library.
Open application/config/autoload.php
and add the database
in libraries array()
.
$autoload['libraries'] = array("database");
3. Model
Create a User_model.php
file in application/models/
folder.
Here, create a method –
- getUsers() – If
search
is POST then fetch all records fromusers
table according to$postData['search']
.
Loop on the fetched records and initialize $response
with value
and label
key.
Return the $response
Array.
Completed Code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class User_model extends CI_Model { function getUsers($postData){ $response = array(); if(isset($postData['search']) ){ // Select record $this->db->select('*'); $this->db->where("username like '%".$postData['search']."%' "); $records = $this->db->get('users')->result(); foreach($records as $row ){ $response[] = array("value"=>$row->id,"label"=>$row->username); } } return $response; } }
4. Controller
Create a User.php
file in application/controllers/
folder.
Here, create 3 methods –
- __construct() – Load
url
helper andUser_model
Model. - index() – Load
user_view
view. - userList() – This method is use to handle AJAX request and return response.
Read the POST values and pass in $this->User_model->getUsers()
to get user records.
Return response in JSON format.
Completed Code
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class User extends CI_Controller { public function __construct(){ parent::__construct(); $this->load->helper('url'); // Load model $this->load->model('User_model'); } public function index(){ // load view $this->load->view('user_view'); } public function userList(){ // POST data $postData = $this->input->post(); // Get data $data = $this->User_model->getUsers($postData); echo json_encode($data); } }
5. View
Create user_view.php
file in application/views/
folder.
Included jQuery UI CSS, JS, and jQuery library.
Create two text elements –
- To initialize jQuery UI autocomplete.
- Display selected user id.
Script –
Initialize autocomplete on #autouser
selector.
Use the source
option to load the suggestion list.
Send AJAX POST request to "<?=base_url()?>index.php/User/userList"
and pass the input value in the text element.
On successful callback pass response data in response()
function.
Using the select
option to get the selected suggestion label and value.
Pass ui.item.label
in #autouser
selector and ui.item.value
in #userid
selector.
Completed Code
<!doctype html> <html> <head> <title>How to Autocomplete textbox in CodeIgniter 3 with jQuery UI</title> <!-- jQuery UI CSS --> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> </head> <body> Search User : <input type="text" id="autouser"> <br><br> Selected user id : <input type="text" id="userid" value='0' > <!-- Script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- jQuery UI --> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <script type='text/javascript'> $(document).ready(function(){ // Initialize $( "#autouser" ).autocomplete({ source: function( request, response ) { // Fetch data $.ajax({ url: "<?=base_url()?>index.php/User/userList", type: 'post', dataType: "json", data: { search: request.term }, success: function( data ) { response( data ); } }); }, select: function (event, ui) { // Set selection $('#autouser').val(ui.item.label); // display the selected text $('#userid').val(ui.item.value); // save selected id to input return false; } }); }); </script> </body> </html>
6. Demo
7. Conclusion
Use source
option to send AJAX request to the controller and load suggestion data.
Return response must have value and label keys.
You can view this tutorial to know how you can add jQuery UI autocomplete in CodeIgniter 4.
If you found this tutorial helpful then don't forget to share.
Hello, I like and use this code. How do I select only if I enter 3 or more characters? At a large database, the selection is very big if I look for the “a” character for example.
Thank you!
Hi Dani,
If you want to search only if textbox has more than 3 characters then just count the length of request.term and execute the AJAX request.
Thank you!
You’re welcome.
Hello,
I like this example but need one that has a dropdown menu in place of the text box once a selection is made the fields below populate with data, do you have an example like this?
Ed
I don’t have an exact tutorial but you can get help with this tutorial.
very effective code.please tell me the questions,,,,,
1.how can i insert the search result id in the database another table.
Hi Razib,
Store the selected user id in a textbox in the
thank you sir
You’re welcome.