Codeigniter 4 jQuery UI Autocomplete Search from Database

jquery ui autocomplete in codeigniter 4 with database; In this tutorial, i will show you how to implement autocomplete search from database in codeigniter 4 using jquery ui & ajax

Jquery ui libray is specially designed for autocomplete search only. You can use this library with different programming languages to create autocomplete searches. In this tutorial you will learn how to implement Autocomplete Suggestive Text Box Search using Jquery and Ajax in codeigniter 4 app.

Autocomplete is a search feature where the search textbox or input predicts the user’s query and provides suggestions as the user types. The user can select any of the autocomplete suggestions and be taken to results without having to manually type every character.

Search with autocomplete textbox from database in codeigniter 4 using jquery ui and ajax example; I will cover following topics:

  • Installing and Setup Codeigniter 4 app
  • Integrate jQuery ui with codeigniter 4 app
  • Integrate Bootstrap 4 with codeigniter 4 app
  • Implement Ajax For Autocomplete Query Search in codeigniter 4 app
  • Implement Search Query From Mysql DB in codeigniter 4 app

jQuery UI Autocomplete Search in Codeigniter 4 with Database

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Database and Table
  • Setup Database Credentials
  • Create Controller
  • Create Views
  • Setup Routes
  • Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to 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 Database and Table

Create a database and table by executing the following SQL query:

CREATE DATABASE demo;

CREATE TABLE users (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email Address',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='demo database' AUTO_INCREMENT=1;

INSERT INTO `users` (`id`, `name`, `email`) VALUES
(1, 'Paul Bettany', '[email protected]'),
(2, 'Vanya', '[email protected]'),
(3, 'Luther', '[email protected]'),
(4, 'John Doe', '[email protected]'),
(5, 'Paul Bettany', '[email protected]'),
(6, 'Vanya', '[email protected]'),
(7, 'Luther', '[email protected]'),
(8, 'Wayne Barrett', '[email protected]'),
(9, 'Vincent Ramos', '[email protected]'),
(10, 'Susan Warren', '[email protected]'),
(11, 'Jason Evans', '[email protected]'),
(12, 'Madison Simpson', '[email protected]'),
(13, 'Marvin Ortiz', '[email protected]'),
(14, 'Felecia Phillips', '[email protected]'),
(15, 'Tommy Hernandez', '[email protected]');

Step 4 – Setup Database Credentials

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'test',
        'password' => '4Mu99BhzK8dr4vF1',
        'database' => 'demo',
        '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,
	];

Step 5 – Create Controller

Create AutocompleteController.php file. So, visit app/Controllers directory and create AutocompleteController.php.Then add the following code into it:

<?php
 
namespace App\Controllers;
 
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
 
class AutocompleteController extends Controller {
 
 
    public function index() {
         
        helper(['form', 'url']);
        return view('autocomplete-search');
    }

    public function getTerm() {

 
        $data = [];

        $db      = \Config\Database::connect();

        $builder = $db->table('users');   

        $query = $builder->like('name', $this->request->getVar('term'))
                    ->select('id, name')
                    ->limit(10)->get();
        $data = $query->getResult();
 
        echo json_encode($data);
    }
  
}

The index() function renders the autocomplete search form db template into the view.

The getTerm() method fetch data form database table.

Step 6 – Create Views

Create autocomplete-search.php view file, so visit application/views/ directory and create autocomplete-search.php file. Then add the following HTML into autocomplete-search.php file:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>jQuery UI Autocomplete  Search in Codeigniter 4 with Database - LaraTutorials.com</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
 <style>
    .container{
    padding: 10%;
    text-align: center;
   } 
 </style>
</head>
<body>
 
<div class="container">
    <div class="row">
        <div class="col-12"><h2>jQuery UI Autocomplete  Search in Codeigniter 4 with Database - LaraTutorials.com</h2></div>
        <div class="col-12">
            <div id="custom-search-input">
                <div class="input-group">
                    <input id="search" name="search" type="text" class="form-control" placeholder="Search" />
                </div>
            </div>
        </div>
    </div>
</div>
<script>
  var BASE_URL = "<?php echo base_url(); ?>";
 
 $(document).ready(function() {
    $( "#search" ).autocomplete({
 
        source: function(request, response) {
            $.ajax({
            url: BASE_URL + "AutocompleteController/getTerm",
            data: {
                    term : request.term
             },
            dataType: "json",
            success: function(data){
               var resp = $.map(data,function(obj){
                    return obj.name;
               }); 
 
               response(resp);
            }
        });
    },
    minLength: 1
 });
});
 
</script>   
</body>
</html>

Step 7 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

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

Step 8 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/

OR

http://localhost:8080/

Conclusion

jquery ui autocomplete in codeigniter 4 with database; In this tutorial,You have learned how to implement autocomplete search from database in codeigniter 4 using jquery ui & ajax.

Recommended CodeIgniter 4 Tutorial

  1. How to Install / Download Codeigniter 4 By Manual, Composer, Git
  2. How to Remove Public and Index.php From URL in Codeigniter 4
  3. Codeigniter 4 Form Validation Example Tutorial
  4. How to add jQuery Validation on Form in Codeigniter 4 Example
  5. Codeigniter 4 Ajax Form Submit Validation Example
  6. Codeigniter 4 File Upload Validation Example
  7. Image Upload with Validation in Codeigniter 4
  8. Codeigniter 4 Image Upload Preview Using jQuery Example
  9. Codeigniter 4 Ajax Image Upload Preview Example
  10. How to Upload Multiple Images in Codeigniter 4
  11. Codeigniter 4 Multiple Image Upload with Preview
  12. Codeigniter 4 Pagination Example; Create Pagination in Codeigniter
  13. Simple Codeigniter 4 CRUD with Bootstrap and MySQL Example
  14. Codeigniter 4 CRUD with Datatables Example
  15. CodeIgniter 4 Server Side DataTable Example
  16. Create Rest Api In Codeigniter 4 App

Be First to Comment

Leave a Reply

Your email address will not be published.