Codeigniter 4 Ajax Autocomplete Search from Database Tutorial

Codeigniter 4 PHP Autocomplete Search tutorial; In this tutorial, you will find some of the easiest instructions to help you create a jQuery autocomplete text search from the database in Codeigniter 4 application. To build this great functionality, we will use the profound jQuery Select2 library.

In this Codeigniter 4 Autocomplete text search example, you will learn how to build text autocomplete search from database in Codeigniter using the JavaScript Select 2 plugin.

Autocomplete is a part of our day-to-day life because we use autocomplete feature on many sites more than often. For instance, we type keywords in the Google search bar, and it is the finest example of autocomplete search.

It gives you word suggestions recklessly based on your search requirement and accurately foretells the word a user thinks to enter after barely several characters have been typed into a form input text. As a result, it exponentially enhances the speed of human-computer interaction.

We will cover all the essential topics which help build autocomplete in Codeigniter. We will walk you through from absolute starting and will help you learn how to integrate autocomplete text box search in Codeigniter with Select 2 package.

Codeigniter 4 jQuery Select2 AJAX Autocomplete Search Example

  • Step 1: Create New Codeigniter Project
  • Step 2: Connect App to Database
  • Step 3: Generate Records Table in Database
  • Step 4: Create View Route
  • Step 5: Register New Controller
  • Step 6: Constitute Autocomplete Search in View
  • Step 7: Run App in Browser

Create New Codeigniter Project

We assume you have already created the app, if not. Head over to the official site and download manually the brand new version of the Codeigniter app.

If you have installed Composer on your computer, you can execute the below command to download the Codeigniter app.

composer create-project codeigniter4/appstarter

Connect App to Database

The second step begins with connecting the app to the database. It is mandatory when it comes to connecting the app to the database.

Get into the app/Config/Database.php, look for $default array, insert your database details in this array.

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

Generate Table with Records in Database

The following code snippet is the SQL query that generates the table also inserts some dummy records into that table.

Make sure to select the database, SQL query tab and execute the command.

--
-- Table structure
--

CREATE TABLE `clients` (
  `id` int(11) NOT NULL COMMENT 'Primary Key',
  `name` varchar(100) NOT NULL COMMENT 'name',
  `email` varchar(100) NOT NULL COMMENT 'description'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Clients collection';

--
-- Dumping data in `clients` table
--

INSERT INTO `clients` (`id`, `name`, `email`) VALUES
(1, 'Carla S Borders', 'borders@hotmail.com'),
(2, 'Linda A Holtz', 'linda@gmail.com'),
(3, 'James T Perry', 'perrry@gmail.com'),
(4, 'Michelle J Waller', 'waller@gmail.com'),
(5, 'Percy R Gurney', 'gurney@gmail.com'),
(6, 'Steven C Mayo', 'mayo@hotmail.com'),
(7, 'Dale E Russell', 'russell@gmail.com'),
(8, 'Joseph K Miner', 'miner@gmail.com'),
(9, 'Brandon P Parker', 'parker@gmail.com'),
(10, 'Jonathan B Woods', 'jonathan@gmail.com'),
(11, 'Jack T Brooke', 'brooke@hotmail.com'),
(12, 'Michael K West', 'michael@gmail.com'),
(13, 'Rita J Matthews', 'matthews@gmail.com'),
(14, 'Lois D Grier', 'grier@gmail.com'),
(15, 'Jennifer J Gonzalez', 'gonzalez@gmail.com');

Create View Route

In this step, you will be adding new routes for making the request to the controller and receiving the response on the browser.

Add code in app/Config/Routes.php.

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/

$routes->setDefaultController('LiveSearchController');
$routes->get('/ajax-autocomplete-search', 'LiveSearchController::index');

Register Autocomplete Controller

In this section, first create a LiveSearchController file, after that define the functions, the confluence of both the functions deals with textbox search in Codeigniter.

Place code in app/Controllers/LiveSearchController.php.

<?php 

namespace App\Controllers;
use CodeIgniter\Controller;


class LiveSearchController extends Controller
{

    public function index() {
        return view('index');
    }
    
    public function getRecords()
    {
        helper(['form', 'url']);

        $records = [];

        $database = \Config\Database::connect();
        $sql = $database->table('clients');   

        $sqlQuery = $sql->like('name', $this->request->getVar('q'))
                    ->select('id, name as text')
                    ->limit(7)->get();
        
        $records = $sqlQuery->getResult();
        
		echo json_encode($records);
    }
 
}

Constitute Autocomplete Search in View

We assume you have created the view file; please add the select2 CSS and javascript in the view file.

Define the select html element, pass the name, tie it with the select2() method, make the request using the controller’s getRecords() method, fetch records from the database, and implement it into the autocomplete module.

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.

Insert code in app/Views/index.php file.

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<title>Codeigniter 4 Select2 Autocomplete Search Example</title>

	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
	<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
</head>

<body>

	<body>
		<div class="container">

			<div class="form-group">
				<select name="search" class="search form-control"></select>
			</div>


			<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
			<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
			<script>
				$('.search').select2({
					placeholder: '----- Search -----',
					ajax: {
						url: '<?php echo base_url('LiveSearchController/getRecords');?>',
						dataType: 'json',
						delay: 355,
						cache: true,
						processResults: function (records) {
							return {
								results: records
							};
						}
					}
				});
			</script>

	</body>

</html>

Run App in Browser

The final task is to start the app and view in the browser, you can do it by using the provided command and the url.

php spark serve
http://localhost:8080/ajax-autocomplete-search

PHP Codeigniter Autocomplete Search

Conclusion

We hope this was an easy-to-follow guide consisting of several instructions that enable you to develop a simplistic autocomplete feature in CodeIgniter at a fast pace.

In this tutorial, you have learned how to implement jQuery select2 in the Codeigniter app to build textbox search or autocomplete search from the database. Furthermore, this example of dynamic autocomplete text search in Codeigniter took you through multiple steps, and I hope you have assimilated it all.