preface

Although CakePHP is no longer used in domestic development, the framework still has a certain market in Japan. I hope this note can help you who are developing in Japan.

Implementation effect

Enter the keywords and display the search results below, which is a single page application

The premise

Readers already have a basic knowledge of CakePHP and JS

version

Cake 3.6.1 PHP 7.4.10

To prepare
  1. Prepare the controller and method
  2. Import JS files in an interface that uses Ajax
  3. Modify JS file, realize front and back end interaction
    • *

      start
      The back-end

      Create Controller, Model, and corresponding Template

  • Create a Controller in <ProjectFolder>\ SRC \Controller

    namespace App\Controller; use App\Controller\AppController; Class SentencesController extends AppController {public $SentencesTable; public function initialize(): void { $this->loadComponent('RequestHandler'); } public function search() {$this-> = $this-> = $this-> = $this->; if ($this->request->is('ajax')) { $data = $this->request->getData(); $results = $this->Sentences->find()->where([ 'sentences_name LIKE' => '%' . $data['keyword'] . '%', 'template_available_lang LIKE' => '%' . $data['lang'] . '%' ])->toList(); If (is_null($results)) {$results = 'No information associated '; } else {// Convert the array to JSON and return it to json_encode($results, json_unescaped_Unicode); exit; }}}
  • Create Sentencestable in <ProjectFolder>\ SRC \Model\Table

    <?php
    namespace App\Model\Table;
    use Cake\ORM\Table;
    class SentencesTable extends Table
    {
        public function initialize(array $config): void
        {
            parent::initialize($config);
            $this->setTable("sentences");
        }
    }
  • Create a custom.ctp file under <ProjectFolder>\ SRC \Template\Layout\

    Search </head> <body> <div class="grid"> // <div id="searchArea"> <input Placeholder =" placeholder "id="searchBox"> < Button id="searchButton </div> </body> // import the js file <? = $this->Html->script([ "serach.js", ]); ? > </html>

    4. Modify the HomeController.php file to specify the above Custom template

    <? php namespace App\Controller; use App\Controller\AppController; class HomeController extends AppController{ public function initialize():void{ parent::initialize(); } public function index(){$this->viewBuilder()->setLayout("custom"); }}
  • Create the index CTP file under the Template folder (the file is blank because the Template is specified)
  • Add routes in Routes.php

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

    The back-end processing is complete at this point

    The front end
  • Create search.js in the <project>\webroot\js\ folder

    $("#searchButton").click(function() {var rawQuery = $("#searchBox").val(); $.ajax({ url: ".. // search", method: 'POST', dataType: 'json', data: {keyword: rawQuery}, data: {keyword: rawQuery}, function(response) { for (var i = 0; i < response.length; I ++) {// Sentence_name is one of the properties of Sentence console.log(response[I]. Sentence_name)}}, // Error in handling sentence_name: function(XMLHttpRequest, textStatus, errorThrown) { console.log('Error : ' + errorThrown + "\n" + XMLHttpRequest.status + "\n" + XMLHttpRequest.statusText + "\n" + textStatus); }}); });

    If you test it out, you’ll get the JSON data

  1. Modify the function processing after success to convert JSON data to HTML *response[I]. The latter are attributes

    success: function (response) { for (var i = 0; i < response.length; i++) { console.log(response[i].template_name); var tr_str = "<tr data-value='" + response[i].title_transfer_flg + "' class='category' id='" + response[i].template_category_id + "'> <td class='list-item' id=" + response[i].id + ">" + response[i].template_name + " < button class = "BTN" id = "title - BTN 'href =' # '> a name に す る < / button > < / td > < / tr >"; $("#result-list").append(tr_str); $("#result-list").append(tr_str); }},

    The final result