###前提・実現したいこと
CakePHP3.5 + Ajaxで検索を行い、検索結果を一覧表示する。
検索項目に更に入力すると絞り込み検索でリアルタイムで結果が変わる様にしたい。イメージとしてはGoogle検索バーの様な感じです。
###発生している問題・エラーメッセージ
indexページでは、postsのデータは全て表示されています。
しかし、検索内容を入力しても、リアルタイムで絞り込み出来ません。
Enterキーを押すと絞り込み結果の画面にジャンプして絞り込み出来ている。
###該当のソースコード
PHP
1# View/Cell/PostCell.php 2 3<?php 4namespace App\View\Cell; 5 6use Cake\View\Cell; 7 8class PostCell extends Cell { 9 public function ajaxSearch() { 10 $this->loadModel('Posts'); 11 12 $keyword = (string)$this->request->query('keyword'); 13 14 $posts = $this->Posts->find('all', [ 15 'conditions' => [ 16 'post_status' => 'publish', 17 'post_title LIKE' => "%$keyword%", 18 ], 19 'limit' => 20, 20 ]); 21 22 $this->set('posts', $posts); 23 } 24}
PHP
1# Template/Cell/Post/ajax_search.ctp 2 3<ul> 4 <?php foreach ($posts as $post): ?> 5 <li><?= $this->Html->link($post->post_title, '/?p=' . $post->ID) ?></li> 6 <?php endforeach ?> 7</ul>
PHP
1# Template/Posts/index.ctp 2 3<?php 4$this->assign('title', '[CakePHP] AJAX リクエストを受けるアクションの実装例'); 5?> 6<div class="content"> 7 <h1>[CakePHP] AJAX リクエストを受けるアクションの実装例</h1> 8 <?php 9 echo $this->Form->create(false, [ 10 'type' => 'get', 11 'id' => 'ajax-search-form', 12 'url' => ['action' => 'ajax_search'], 13 ]); 14 echo $this->Form->input('keyword', ['label' => '記事名で検索']); 15 echo $this->Form->end(); 16 17 $fragment = $this->cell('Post::ajaxSearch')->render(); 18 ?> 19 <div id="ajax-search-result"><?= $fragment ?></div> 20</div> 21<?= $this->Html->script('ajax') ?>
PHP
1# Template/Posts/ajax_search.ctp 2 3<?= $this->cell('Post::ajaxSearch')->render() ?>
PHP
1# Controller/PostsController.php 2 3<?php 4namespace App\Controller; 5 6use App\Controller\AppController; 7use Cake\Network\Exception\ForbiddenException; 8 9class PostsController extends AppController { 10 11 public function index() { 12 } 13 14 public function ajaxSearch() { 15 if (!$this->request->is(['ajax'])) { 16 17 } 18 $this->viewBuilder()->layout(false); 19 } 20}
参照のデータベース
SQL
1CREATE TABLE `posts` ( 2 `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 3 `title` varchar(255) DEFAULT NULL, 4 `body` text, 5 `created` datetime DEFAULT NULL, 6 `modified` datetime DEFAULT NULL, 7 `post_title` varchar(50) DEFAULT NULL, 8 `post_status` int(11) DEFAULT NULL, 9 `name` varchar(50) DEFAULT NULL, 10 PRIMARY KEY (`id`) 11) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
###試したこと
下記サイトを参考に作成してみました。
https://mbstring.com/techniques/ajax/
###補足情報(言語/FW/ツール等のバージョンなど)
CakePHP3.5
VirtualBox
Vagrant
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。