Autocomplete Search Text box using Typeahead in Codeigniter 4

Step 1: Download the typeahead library from the following link:

https://github.com/twitter/typeahead.js

Step 2: Extract the downloaded typeahead library and copy the typeahead.js file and paste it into the public/js folder of your Codeigniter 4 project.

Step 3: Create a view file in the application/views folder and add the following code to it:




Autocomplete Search Textbox using Typeahead in Codeigniter 4






Step 4: Create a controller file in the application/controllers folder and add the following code to it:

request->getVar(‘query’);

$data = [
‘India’,
‘Indonesia’,
‘United States’,
‘United Kingdom’,
‘Australia’,
‘Canada’,
‘China’,
‘Japan’,
‘South Korea’,
‘Malaysia’,
‘Singapore’,
‘Thailand’,
‘Vietnam’
];

$result = [];

if($query) {
foreach($data as $country) {
if(strpos(strtolower($country), strtolower($query)) !== false) {
array_push($result, $country);
}
}
}

echo json_encode($result);
}
}

Step 5: Now, open the browser and go to the following URL:

http://localhost/autocomplete

You should see the autocomplete search textbox. Try typing a country name and you should see the autocomplete suggestions.

Autocomplete textbox search from database in codeigniter 4 using jQuery Typeahead js. In this tutorial, you will learn how to implement an autocomplete search or textbox search with database using jquery typehead js example.

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

Autocomplete Search Text box using Typeahead in Codeigniter 4

Let’s follow the following steps to implement autocomplete textbox from database using Typehead js in CodeIgniter 4 apps:

  • Step 1: Setup Codeigniter Project
  • Step 2: Basic Configurations
  • Step 3: Create a Table in the Database
  • Step 4: Setup Database Credentials
  • Step 5: Create a Controller
  • Step 6: Create a View
  • Step 7: Define Routes
  • Step 8: Start Development Server

Step 1: Setup Codeigniter Project

In this step, you will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

Step 2: Basic Configurations

Next, you will set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

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

Step 3: Create a Table in the Database

In this step, you need to create table in database and as well as insert some data to implement an autocomplete search app in codeiginter 4. So visit your phpmyadmin panel and execute the following sql query in it:

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');

Step 4: Setup Database Credentials

In this step, you need to connect our project to the database. you need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, you need to set up database credentials in this file like below.

	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 a Controller

In this step, Visit app/Controllers and create a controller name AutocompleteSearch.php. In this controller, you need to add the following methods into it:

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

}

Step 6: Create a View

In this step, you need to create one view files name home.php and update the following code into your file:

<html lang="en">
<head>
    <title>Codeigniter 4 - jquery ajax autocomplete search using typeahead example- Tutsmake.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- Tutsmake.com</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>

Step 7: Define Routes

In this step, you 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');

Step 8: Start Development Server

In this step, open your terminal and execute the following command to start development sever:

php spark serve

Then, Go to the browser and hit below the URL:

http://localhost:8080

Conclusion

In this Codeigniter 4 autocomplete search using jquery typeahead js example. In this tutorial you have successfully learned how to make autocomplete search using typeahead js in codeigniter 4.

Recommended Codeigniter Posts

If you have any questions or thoughts to share, use the comment form below to reach us.

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?