How to Autocomplete textbox in CodeIgniter with jQuery UI

Autocomplete textbox gives the suggestions based on the user input.

This generally uses in the field where a user needs to select an item from the available data.

In this tutorial, to add autocomplete on a textbox element I am using jQuery UI in CodeIgniter.

How to autocomplete textbox in CodeIgniter with jQuery UI


Contents

  1. Table structure
  2. Configuration
  3. Model
  4. Controller
  5. View
  6. Demo
  7. Conclusion

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 Users.

$route['default_controller'] = 'Users';

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 methods –

  • 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();

     $this->db->select('*');

     if($postData['search'] ){

       // Select record
       $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 Users.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

<?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/ 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 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="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/Users/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

Input some characters in the textbox.


7. 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 Post

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *