Autocomplete Select2 Textbox with multiple selection using jquery in Codeigniter 4

Autocomplete Select2 Textbox with multiple selection using jquery in Codeigniter 4

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

This tutorial will show you step by step how to implement jquery and select2 autocomplete search from database in codeigniter 4 app.

Autocomplete Select2 Textbox with multiple selection using jquery in Codeigniter 4

  • 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 file name home.php and update the following code into your file:

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

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>how to make autocomplete search using jquery in codeigniter 4 - tutsmake.com</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

  <style>
    .container {
      max-width: 500px;
    }
  </style>
</head>

<body>
  <div class="container mt-5">

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

  </div>
</body>

<script>
      $('.search').select2({
        placeholder: '--- Search User ---',
        ajax: {
          url: '<?php echo base_url('AutocompleteSearch/ajaxSearch');?>',
          dataType: 'json',
          delay: 250,
          processResults: function(data){
            return {
              results: data
            };
          },
          cache: true
        }
      });
</script>

</html>

Step 7: Define Routes

In this step, you need to create a route that renders the table into the view, and 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 and select2 example. In this tutorial, you have successfully learned how to make autocomplete search using jquery and select2 in codeigniter 4.

You can check out the demo here :- Codeigniter 4 autocomplete search from database demo.

Recommended Codeigniter Tutorials

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

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

One reply to Autocomplete Select2 Textbox with multiple selection using jquery in Codeigniter 4

  1. Thanks for this blog

Leave a Reply

Your email address will not be published. Required fields are marked *