Codeigniter 4 Autocomplete Textbox From Database using Typeahead JS

Codeigniter 4 Autocomplete Textbox From Database using Typeahead JS

Codeigniter – Typeahead.js is a lightweight JavaScript library used for providing fast and autocomplete suggestions from a database as the user types into an input field. It has been around since Twitter’s Bootstrap 3 was released in 2013 and has become one of the most popular front-end libraries available today.

In this tutorial, we’ll show you how to use Typeahead.js with Codeigniter to provide quick, database-based autocomplete suggestions for your web application. We’ll also cover some of the basic configuration options that Typeahead.js offers to customize its behaviors.

Autocomplete textbox is a great feature for providing suggestions to users as they type. It can be used for things like providing search results or suggested products as a user types into a search box. In this tutorial, we’ll show you how to implement autocomplete textbox in Codeigniter 4 using the Typeahead JS library.

Typeahead is a lightweight JavaScript library that provides suggestions as you type. It works with local data or remote data via Ajax request. For our example, we’ll use local data since we just want to show a list of suggested items as the user types into the textbox.

Here’s how our autocomplete textbox will work:

The user will type something into the textbox. As they type, Typeahead will make an Ajax request to our Codeigniter 4 controller and pass the typed string as a query parameter. Our controller will then fetch records from the database that match the typed string and return them as JSON data. Typeahead will take care of displaying the returned data in the dropdown list for us.

How to Implement Autocomplete Textbox in Codeigniter 4

Here are following steps to implement autocomplete textbox in Codeigniter 4

  • Download Codeigniter Latest

  • Basic Configurations

  • Create Table and Database

  • Setup Database Credentials

  • Create Controller

  • Create View

  • Create Route

  • Start Development Server

  • Conclusion

Download Codeigniter Latest

To get started with CodeIgniter 4, the first step is to download the latest version of the framework. You can download the framework from the official CodeIgniter website at https://codeigniter.com/download.

Once you have downloaded the CodeIgniter 4 setup, unzip the archive and save it in your local system. You can save it in the XAMPP/htdocs/ directory if you are using XAMPP as your local development environment.

Basic Configurations

Now, we need to configure some basic settings in the “app/config/app.php” file. To do this, we will open the “config.php” file located in the “application/config” folder using a text editor.

Set Base Url Like This

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Create Table And Database

Now we need to create a database with the name ‘demo’. To do this, we’ll open PHPMyAdmin and create a new database with that name.

Once you’ve successfully created the database, you can use the following SQL query to create a ‘users’ table within the database.

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, 'John Doe'),
(2, 'Vanya'),
(3, 'Luther'),
(4, 'Diego'),
(5, 'Klaus'),
(6, 'Ben'),
(7, 'Handler'),
(8, 'Dexter'),
(9, 'Mask'),
(10, 'Aladin');

Setup Database Credentials

Now, we need to connect our CodeIgniter 4 project to the database. To do this, we will open the “database.php” file located in the “app/Config” folder using a text editor.

public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,
];

Create Controller

Next, let’s go to the ‘app/Controllers’ folder and create a new controller named ‘AutocompleteSearch.php’. Within this controller, we’ll create two methods or functions:

<?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);
    }

}

Create Views


<html lang="en">
<head>
    <title>Codeigniter 4 - jquery ajax autocomplete search using typeahead example- torqueprogramming.co.in</title>  
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>  
</head>
<body>


<div class="container">
    <h1>Codeigniter 4 - jquery ajax autocomplete search using typeahead example- torqueprogramming.co.in</h1>
    <input class="typeahead form-control" type="text">
</div>


<script type="text/javascript">
    $('input.typeahead').typeahead({
        source:  function (query, process) {
        return $.get('/AutocompleteSearch/ajaxSearch', { query: query }, function (data) {
                console.log(data);
                data = $.parseJSON(data);
                return process(data);
            });
        }
    });
</script>


</body>
</html>

Next step, we need to create one view file name home.php under the views folder and update the following code into your file:

Create Route

Next step, we need to create a route that renders the table into the view, place the following code in app/Config/Routes.php file.

$routes->get('/', 'AutocompleteSearch::index');