Codeigniter 4 - Autocomplete Textbox From Database Example

Apr 21, 2022 . Admin



Hi Dev,

This post is focused on autocomplete search box using typeahead in codeigniter 4 example. Here you will learn autocomplete search box in codeigniter 4 tutorial. you can see codeigniter 4 autocomplete textbox from database using typeahead js example. this example will help you autocomplete search box using typeahead js in codeigniter 4.

In this tutorial i will show you step by step how to implement autocomplete search from database in codeigniter 4 app using typeahead js.

Step 1: Install Codeigniter 4

If you have not created the codeigniter app, then you maygo ahead and execute the below command:

composer create-project codeigniter4/appstarter ci-news
Step 2 : Basic Configurations

So, we will now set the basic configuration on the app/config/app.php file, so let’s implement to application/config/config.php and open this file on text editor.

app/config/app.php
public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/example/';
Step 3 : Database Configurations
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, 'Bhavesh'),
(2, 'Mehul'),
(3, 'Piyush'),
(4, 'Savan'),
(5, 'Klaus'),
(6, 'Ben'),
(7, 'Handler'),
(8, 'Dexter'),
(9, 'Mask'),
(10, 'Aladin');
Step 4 : Database Configurations application/config/database.php
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,
];
Step 5: Create Controller

In this step,we will create to TypeheadSearch in app/Controllers folder.

app/Controllers/TypeheadSearch.php
<?php 
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
 
class TypeheadSearch extends Controller
{

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index() {
        return view('home');
    }
     
    /**
     * Write code on Method
     *
     * @return response()
     */
    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);
    }
 
}
Step 6: Define Route

We have to engender a route that renders the table into the view, place the following code in app/Config/Routes.php file.

app/Config/Routes.php
$routes->get('/', 'TypeheadSearch::index');
Step 7: Create View

we have to create a home.php file that we will use to convert HTML to PDF. Place the following code inside the application/views/home.php file.

<html lang="en">
<head>
    <title>Codeigniter 4 jQuery ajax autocomplete search using typeahead example- Mywebtuts.com</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- Mywebtuts.com</h1>
    <input class="typeahead form-control" type="text">
</div>
 
<script type="text/javascript">

    /*------------------------------------------
    --------------------------------------------
    Autocomplete Search 
    --------------------------------------------
    --------------------------------------------*/
    $('input.typeahead').typeahead({
        source:  function (query, process) {
        return $.get('/TypeheadSearch/ajaxSearch', { query: query }, function (data) {
                console.log(data);
                data = $.parseJSON(data);
                return process(data);
            });
        }
    });
</script>
 
</body>
</html>
Step 8 : Run Codeigniter App: All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:
php spark serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8080/

It will help you...

#Codeigniter 4