CakePHP 4 Load Data using jQuery Ajax in Select2

Reading Time: 8 minutes

Inside this article we will use the concept of select2 jquery plugin to load dynamic data using ajax in CakePHP 4. Article contains classified information about loading data into select2 plugin via ajax request.

How to Load data using jQuery AJAX in Select2 using CakePHP 4, we will see in a clear way here.

Select2 is a jquery plugin which alters HTML element and create dynamic element with ajax data. Select2 also contains itself a search function into it. This tutorial will cover all easy steps to integrate and implement this functionality.

Learn More –

Let’s get started.

CakePHP 4 Installation

To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.

Create Database

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


Successfully, we have created a database.

Database Connection

Open app_local.php file from /config folder. Search for Datasources. Go to default array of it.

You can add your connection details here to connect with your database. It will be like this –


'Datasources' => [
        'default' => [
            'host' => 'localhost',
             * CakePHP will use the default DB port based on the driver selected
             * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
             * the following line and set the port accordingly
            //'port' => 'non_standard_port_number',

            'username' => 'root',
            'password' => 'sample@123',

            'database' => 'mydatabase',
             * If not using the default 'public' schema with the PostgreSQL driver
             * set it here.
            //'schema' => 'myapp',

             * You can use a DSN string to set the entire configuration
            'url' => env('DATABASE_URL', null),


You can pass host, username, password and database.

Successfully, you are now connected with the database.

Create Migration

Open project into terminal and run this commands to create migration file.

$ bin/cake bake migration CreateCountries

It will create 20220330143909_CreateCountries.php file inside /config/Migrations folder.

Open migration file and write this following code into it. The code is all about for the schema of countries table.



use Migrations\AbstractMigration;

class CreateCountries extends AbstractMigration
    public function change()
        $table = $this->table('countries');

        $table->addColumn("name", "string", [
            "limit" => 120,
            "null" => false

        $table->addColumn("sortname", "string", [
            "limit" => 50,
            "null" => false

        $table->addColumn("phonecode", "string", [
            "limit" => 20,
            "null" => false


Run Migration

Back to terminal and run this command.

$ bin/cake migrations migrate

It will create table “countries” inside database.

Insert Test 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.

Here, you need to copy mysql query from this given file and run into sql tab of phpmyadmin. First download it and run.

You will see something like this after this test data insertion.

countries” table

Create Controller

Open project into terminal and run this command into it.

$ bin/cake bake controller Search --no-actions

It will create SearchController.php file inside /src/Controller folder. Open controller file and write this code into it.



namespace App\Controller;

use Cake\Datasource\ConnectionManager;

class SearchController extends AppController
    private $db;

    public function initialize(): void
        $this->db = ConnectionManager::get("default");

    public function searchForm()
        // open frontend view

    public function searchCountry()
        if ($this->request->is("ajax")) {

            $searchQuery = $this->request->getData("query");

            $countriesList = [];

            if (isset($searchQuery) && !empty($searchQuery)) {

                // Fetch record with search query
                $countries = $this->db->execute("SELECT id, name from countries WHERE name like '%" . $searchQuery . "%'")->fetchAll("assoc");
            } else {

                // Fetch record
                $countries = $this->db->execute("SELECT id, name from countries")->fetchAll("assoc");

            foreach ($countries as $country) {
                $countriesList[] = array(
                    "id" => $country['id'],
                    "text" => $country['name'],

            echo json_encode(array(
                "status" => 1,
                "data" => $countriesList


Above controller class contains three methods:

  • initialize() constructor which loads the instance for database connection.
  • searchForm() which is for frontend layout for select2 dropdown view.
  • searchCountry(), this method will be hit by ajax request when we search into select2 dropdown.

Create Template

Create Search folder inside /templates folder. Next, needs to create search_form.php file inside /templates/Search folder.

Open search_form.php file and write this following code into it. This will give the frontend layout for Select2 view.

<!DOCTYPE html>


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

    <link rel="stylesheet" href="">

    <!-- jQuery -->
    <script src=""></script>

    <link href="" rel="stylesheet" />

    <script src=""></script>


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

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

            // Initialize select2
                ajax: {
                    url: "/list-countries",
                    type: "post",
                    delay: 250,
                    dataType: 'json',
                    data: function(params) {
                        return {
                            query: params.term, // search term
                    processResults: function(response) {
                        return {
                    cache: true




Disable CSRF Token

When we submit a cakephp form, it needs a CSRF token should be submitted with form submission request.

We are not interested to send CSRF token with form data. To disable it, Open Application.php from /src folder.

Remove these lines of code from middleware() method.

->add(new CsrfProtectionMiddleware([
    'httponly' => true,

Add Route

Open routes.php file from /config folder. Add these routes into it.


    ['controller' => 'Search', 'action' => 'searchForm']

    ['controller' => 'Search', 'action' => 'searchCountry']


Application Testing

Open terminal and run this command to start development server.

$ bin/cake server

URL: http://localhost:8765/search-form

When we search any country into Select2 list, it will fire an ajax request with search term –

We hope this article helped you to learn about CakePHP 4 Load Data using jQuery AJAX in Select2 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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more