CodeIgniter 4 How To Load Data Using jQuery Ajax in Select2

Reading Time: 6 minutes
9,162 Views

Select2 is a versatile library that enhances HTML select elements by providing search, remote data loading, and customizable features. In CodeIgniter 4, integrating Select2 with jQuery Ajax offers a powerful way to load dynamic data into select elements, enabling users to efficiently search and select information.

In this tutorial, we’ll see the comprehensive process of loading data using jQuery Ajax in Select2 within CodeIgniter 4. This functionality empowers developers to create interactive select elements that fetch and display data dynamically from the server.

Read More: How To Work with Filters in CodeIgniter 4 Tutorial

Let’s get started.

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.

Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.

Read More: Concept of Query Grouping in CodeIgniter 4 Tutorial

Create Database Table

Next, we need a table. That table will be responsible to store data.

CREATE TABLE `countries` (
 `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
 `iso` char(2) COLLATE utf8mb4_unicode_ci NOT NULL,
 `name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
 `nicename` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
 `iso3` char(3) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `numcode` smallint(6) DEFAULT NULL,
 `phonecode` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Successfully, we have created a table.

Database Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string values.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = admin
database.default.password = admin
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306
  

Now, database successfully connected with the application.

Insert Data into Table

As we have created a table named as countries. We need some data into this table to test jQuery Select2 plugin.

For data here we have the link of github.

Run the given mysql query to your database from this github link.

When you will run, you will get data something like this.

Create Controller

Back to terminal and run this command to create controller file.

php spark make:controller Search --suffix

It will create SearchController.php file inside /app/Controllers folder.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class SearchController extends BaseController
{
	public function __construct()
	{
		$this->db = db_connect();
	}

	public function index()
	{
		return view('search');
	}

	public function getCountries()
	{
		$request = service('request');
		$postData = $request->getPost(); // OR $this->request->getPost();

		$response = array();

		$data = array();

		$builder = $this->db->table("countries");

		$countries = [];

		if (isset($postData['query'])) {

			$query = $postData['query'];

			// Fetch record
			$builder->select('*');
			$builder->like('nicename', $query, 'both');
			$query = $builder->get();
			$data = $query->getResult();
		} else {

			// Fetch record
			$builder->select('*');
			$query = $builder->get();
			$data = $query->getResult();
		}

		foreach ($data as $country) {
			$countries[] = array(
				"id" => $country->id,
				"text" => $country->nicename,
			);
		}

		$response['data'] = $countries;

		return $this->response->setJSON($response);
	}
}

Read More: MySQL Group By in CodeIgniter 4 Query Builder Tutorial

Add Routes

Open Routes.php file from /app/Config folder. Add these routes into it.

//..

$routes->get('data', 'SearchController::index');
$routes->post('countries', 'SearchController::getCountries');

//..

Download Select2 CDN

  • Download the select2 plugin from here.
  • Extract it in the public/ folder at the root.
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

Create Layout File

Create search.php file inside /app/Views folder.

Open file and write this complete code into it.

<!DOCTYPE html>
<html>

<head>

    <title>How to Load data using jQuery AJAX in Select2 – CodeIgniter 4</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

    <!-- jQuery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
</head>

<body>

    <div class="container" style="margin-top: 40px;">
        <div class="panel panel-primary">
            <div class="panel-heading">CodeIgniter 4 Load Data using jQuery AJAX in Select2</div>
            <div class="panel-body">
                <p>
                    <label>Select Country</label>
                </p>
                <select name="dd_country" id="dd_country" class="form-group">
                    <option value='0'>-- Select country --</option>
                </select>
            </div>
        </div>
    </div>

    <!-- Script -->
    <script type='text/javascript'>
        $(document).ready(function() {

            // Initialize select2
            $("#dd_country").select2({
                ajax: {
                    url: "<?= site_url('countries') ?>",
                    type: "post",
                    delay: 250,
                    dataType: 'json',
                    data: function(params) {
                        return {
                            query: params.term, // search term
                        };
                    },
                    processResults: function(response) {
                        return {
                            results: response.data
                        };
                    },
                    cache: true
                }
            });

        });
    </script>

</body>

</html>

Application Testing

Open project terminal and start development server via command:

php spark serve

URL: http://localhost:8080/data

That’s it.

We hope this article helped you to learn about CodeIgniter 4 How To Load Data Using jQuery Ajax in Select2 Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.