How to Autocomplete textbox in CodeIgniter with jQuery UI

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.

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

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/ directory.

Here, create a method –

  • getUsers() – If search is POST then fetch all records from users 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/ directory.

Here, create 3 methods –

  • __construct() – Load url helper and User_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

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/ directory.

Included jQuery UI CSS, JS, and jQuery library.

Create two text elements –

  1. To initialize jQuery UI autocomplete.
  2. 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 with jQuery UI</title> <!-- jQuery UI CSS --> <link rel="stylesheet" href=""> </head> <body> Search User : <input type="text" id="autouser"> <br><br> Selected user id : <input type="text" id="userid" value='0' > <!-- Script --> <script src=""></script> <!-- jQuery UI --> <script src=""></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>

6. Conclusion

Use source option to send AJAX request to the controller and load suggestion data.

Return response must have value and label keys.

If you found this tutorial helpful then don’t forget to share.

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

Related Posts