CakePHP 4 Load Data using jQuery Ajax in Select2

Share this Article
Reading Time: 8 minutes
1,947 Views

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.

CREATE DATABASE mydatabase;

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.

<?php

declare(strict_types=1);

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
        ]);

        $table->create();
    }
}

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.

<?php

declare(strict_types=1);

namespace App\Controller;

use Cake\Datasource\ConnectionManager;

class SearchController extends AppController
{
    private $db;

    public function initialize(): void
    {
        parent::initialize();
        $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
            ));

            die;
        }
    }
}

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>
<html>

<head>

    <title>How to Load data using jQuery AJAX in Select2 – CakePHP 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">CakePHP 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: "/list-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>

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.

//...

$routes->connect(
    '/search-form',
    ['controller' => 'Search', 'action' => 'searchForm']
);

$routes->connect(
    '/list-countries',
    ['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.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

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.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5