https://www.sejuku.net/blog/31050
こちらの記事を参考にしてajaxでデータベースにデータを登録しようとすると、
Error : Forbiddenが出てしまいます。
ググると「config/routes.php」や「src/Application.php」のCSRFチェックの処理を書き替えるとよいと出るのですが、
うまくいきません。
https://www.sejuku.net/blog/31050
https://www.sejuku.net/blog/31050
なにか解決する方法がわかる方いましたら知恵をお貸しください。
よろしくお願いいたします。
index.php
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8" /> <title>jQuery・Ajax・Cake</title> <?php // Ajax 送信用の JavaScript を読み込み echo $this->Html->script('http://code.jquery.com/jquery-1.11.3.min.js'); //echo $this->Html->script('send_data'); echo $this->Html->script($ajax_name); ?> </head> <body> <h1>jQuery・Ajax・Cake</h1> <?= $this->Form->create() ?> <?php echo $this->Form->textarea("textdata",['cols'=> 20, 'rows' => 4,'id' => 'textdata']); ?> <?= $this->Form->submit('送信',['id' => 'send']) ?> <?= $this->Form->end() ?> </body> </html>
DatasController.php
<?php declare(strict_types=1); namespace App\Controller; use App\Controller\AppController; use Cake\Datasource\ConnectionManager; use Cake\Event\Event; class DatasController extends AppController { public function index() { $this->set('ajax_name','send_data.js'); } public function add(){ $data = $this->request->data('request'); $connection = ConnectionManager::get('default'); $connection->insert('datas', [ 'text' => $data ]); } }
send_data.js
$(document).ready(function() { /** * 送信ボタンクリック */ $('#send').click(function() { var data = { request : $('#textdata').val() }; alert( $('#textdata').val() ); $.ajax({ type: 'POST', datatype:'json', url: "/kamedaapp/datas/add.json", data: data, success: function(data,dataType) { alert('Success'); }, /** * Ajax通信が失敗した場合に呼び出されるメソッド */ error: function(XMLHttpRequest, textStatus, errorThrown) { alert('Error : ' + errorThrown); } }); return false; }); });
Application.php
<?php declare(strict_types=1); namespace App; use Cake\Core\Configure; use Cake\Core\ContainerInterface; use Cake\Core\Exception\MissingPluginException; use Cake\Datasource\FactoryLocator; use Cake\Error\Middleware\ErrorHandlerMiddleware; use Cake\Http\BaseApplication; use Cake\Http\Middleware\BodyParserMiddleware; use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Http\MiddlewareQueue; use Cake\ORM\Locator\TableLocator; use Cake\Routing\Middleware\AssetMiddleware; use Cake\Routing\Middleware\RoutingMiddleware; class Application extends BaseApplication { public function bootstrap(): void { // Call parent to load bootstrap from files. parent::bootstrap(); if (PHP_SAPI === 'cli') { $this->bootstrapCli(); } else { FactoryLocator::add( 'Table', (new TableLocator())->allowFallbackClass(false) ); } if (Configure::read('debug')) { $this->addPlugin('DebugKit'); } // Load more plugins here } /** * Setup the middleware queue your application will use. * * @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup. * @return \Cake\Http\MiddlewareQueue The updated middleware queue. */ public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue { $middlewareQueue ->add(new ErrorHandlerMiddleware(Configure::read('Error'))) ->add(new AssetMiddleware([ 'cacheTime' => Configure::read('Asset.cacheTime'), ])) ->add(new RoutingMiddleware($this)) ->add(new BodyParserMiddleware()) ->add(new CsrfProtectionMiddleware([ 'httponly' => true, ]) ); return $middlewareQueue; } /** * Register application container services. * * @param \Cake\Core\ContainerInterface $container The Container to update. * @return void * @link https://book.cakephp.org/4/en/development/dependency-injection.html#dependency-injection */ public function services(ContainerInterface $container): void { } /** * Bootstrapping for CLI application. * * That is when running commands. * * @return void */ protected function bootstrapCli(): void { try { $this->addPlugin('Bake'); } catch (MissingPluginException $e) { // Do not halt if the plugin is missing } $this->addPlugin('Migrations'); // Load more plugins here } }
routes.php
<?php use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; use Cake\Routing\Router; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { Router::scope('/',function($routes){ $routes->setExtensions(['json']); $routes->connect('/datas/get',['controller'=>'Datas','action'=>'get'])->setMethods(['GET']); $routes->connect('/datas/add',['controller'=>'Datas','action'=>'add'])->setMethods(['POST']); // $routes->resources('Datas'); }); $builder->connect('/', ['controller' => 'Datas', 'action' => 'display', 'home']); $builder->connect('/pages/*', 'Pages::display'); $builder->fallbacks(); }); // use Cake\Routing\Route\DashedRoute; // use Cake\Routing\RouteBuilder; // use Cake\Routing\Router; // $routes->setRouteClass(DashedRoute::class); // $routes->scope('/', function (RouteBuilder $builder) { // Router::scope('/',function($routes){ // $routes->setExtensions(['json']); // $routes->connect('/datas/get',['controller'=>'Datas','action'=>'get'])->setMethods(['GET']); // $routes->connect('/datas/regist',['controller'=>'Datas','action'=>'regist'])->setMethods(['POST']); // // $routes->resources('Datas'); // }); // $builder->connect('/', ['controller' => 'Datas', 'action' => 'index']); // $builder->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']); // $builder->fallbacks(); // });
回答1件
あなたの回答
tips
プレビュー