CodeIgniter 4 AJAX Tutorial
    About Lesson

    To create an autocomplete example in CodeIgniter 4, follow these steps:

     

    Step 1: Database Setup

    CREATE TABLE `state_info` (
      `id` int(11) NOT NULL,
      `country_id` varchar(10) NOT NULL,
      `name` varchar(100) NOT NULL,
      `tin` varchar(10) NOT NULL,
      `code` varchar(100) NOT NULL,
      `ip_address` varchar(100) DEFAULT NULL,
      `created_at` datetime DEFAULT NULL,
      `updated_at` timestamp NULL DEFAULT NULL,
      `status` varchar(10) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
    ALTER TABLE `state_info`
      ADD PRIMARY KEY (`id`);

     

    Step 2: Controller

    Create a controller to handle CRUD operations. Create a new file named Autocomplete.php in the app/Controllers/autocompletefolder.

    <?php
    namespace App\Controllers\autocomplete;

    use App\Controllers\BaseController;
    use App\Models\state\StateModel;

    class Autocomplete extends BaseController {

    public function __construct() {
    $db = db_connect();
    $this->state = new StateModel($db);
    }

    public function index() {
    $this->find();
    }

    public function find() {
    $data = [];
    $data ['content_title'] = "Autocomplete Example";
    $data ['main_content'] = "autocomplete/find";
    echo view('innerpages/template', $data);
    }

    public function search() {
    $keyword = $this->request->getPost('keyword');
    $where = 'name LIKE "%'.$keyword.'%"';
    $result = $this->state->getEntryList($where);
    $list = [];
    foreach($result as $row) {
    $list [] = [
    'id' => $row->id,
    'value' => $row->name,
    ];
    }
    echo json_encode($list);
    }
    }

     

    Step 3: Model

    Create a model to handle database operations. Create a new file named StateModel.php in the app/Models/statefolder.

    <?php
    namespace App\Models\state;

    use CodeIgniter\Model;
    use CodeIgniter\Database\ConnectionInterface;

    class StateModel extends Model {

    protected $db;

    public function __construct(ConnectionInterface &$db) {
    $this->db =& $db;
    $this->table = 'state_info';
    }

    public function addEntry($data) {
    $this->db->table($this->table)
    ->insert($data);
    return $this->db->insertID();
    }

    public function getEntry($where) {
    return $this->db->table($this->table)
    ->where($where)
    ->get()
    ->getRow();
    }

    public function getEntryList($where = 0) {
    if($where) {
    return $this->db->table($this->table)
    ->where($where)
    ->get()
    ->getResult();
    } else {
    return $this->db->table($this->table)
    ->get()
    ->getResult();
    }

    }

    public function updateEntry($where, $data) {
    return $this->db->table($this->table)
    ->where($where)
    ->set($data)
    ->update();
    }

    public function deleteEntry($where) {
    return $this->db->table($this->table)
    ->where($where)
    ->delete();
    }
    }
     

     

    Step 4: Create Views

    Create views (find.php) in the app/Views/autocomplete folder for listing, creating, updating, and deleting records.

    find.php

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

    <head>
    <title>
    <?php echo $content_title; ?>
    </title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"></link>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <!-- Autocompelete -->
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>

    </head>

    <body>
    <div class="container">
    <div class="jumbotron">
    <h1>Autocomplete Example </h1>
    <p>CodeIgniter 4.</p>
    </div>
    <div class="row">
    <div class="col-sm-12">
    <div class="form-group">
    <label>Enter Keywords</label>
    <input type="text" name="keyword" id="keyword" class="form-control" placeholder="Enter keywords" autocomplete="off" required>
    </div>

    </div>
    </div>
    </div>
    <script>
    $(document).ready(function() {

    $("#keyword").autocomplete({
    source: function(request, response) {
    $.post('<?php echo base_url("autocomplete/search"); ?>', {keyword : request.term}, function(result) {
    response(result);
    }, 'json')
    },
    minLength: 1,
    select: function( event, ui ) {
    console.log( "Selected: " + ui.item.value + " aka " + ui.item.id );
    }
    });

    });
    </script>
    </body>

    </html>

     

    Step 5: Set Up Routes

    Edit the app/config/Routes.php file to define routes for your controller.

    // autocomplete
    $routes->get('autocomplete/find', 'autocomplete\Autocomplete::find');
    $routes->post('autocomplete/search', 'autocomplete\Autocomplete::search');

     

    Step 6: Run Project & Output

     

    CodeIgniter 4 - autocomplete