I have an action called ajaxDelete($id = null)
I am using JQuery AJAX on a button to delete uploaded file in Edit page.
If I use GET method with url : http://host/app/or-uploads/ajax-delete/2.json then the record #2 got deleted and success result returned as expected. (of course the allowMethod part is commented out)
If I user POST method with url : http://host/app/or-uploads/ajax-delete.json then i got error message in browser console:
POST http://host/app/or-uploads/ajax-delete.json 403 (Forbidden)
My action is below:
public function ajaxDelete()
{
$this->request->allowMethod(['post', 'delete']);
$id = $this->request->getData('upload_id');
$orUpload = $this->OrUploads->get($id);
if ($this->OrUploads->delete($orUpload)) {
$message = __('The OR upload file has been deleted.');
$result = true;
} else {
$message = __('The OR upload file could not be deleted. Please, try again.');
$result = false;
$this->set(compact('error'));
}
$this->set('message', $message);
$this->set('result', $result);
$this->viewBuilder()->setOption('serialize', ['message', 'result']);
}
what did i do wrong?
Are you certain your route/URL is connected to that controller action and not another one? I’d check via bin/cake routes
or the debug_kit toolbar.
I am sure the Route is connected to that Controller.
I did not configure any custom route at all, except 3 old routes which are not using anymore point to home, just in case users keep bookmark on their browsers.
Below are my routes.php
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
/*
* Here, we are connecting '/' (base path) to a controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, templates/Pages/home.php)...
*/
$builder->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
$builder->connect('/wfh', ['controller' => 'Pages', 'action' => 'display', 'home']);
$builder->connect('/timesheets/statistic', ['controller' => 'Pages', 'action' => 'display', 'home']);
$builder->connect('/timesheets', ['controller' => 'Pages', 'action' => 'display', 'home']);
/*
* ...and connect the rest of 'Pages' controller's URLs.
*/
$builder->connect('/pages/*', 'Pages::display');
$builder->setExtensions(['json', 'xml', 'pdf']); //THA added from instruction https://github.com/FriendsOfCake/CakePdf
/*
* Connect catchall routes for all controllers.
*
* The `fallbacks` method is a shortcut for
*
* ```
* $builder->connect('/:controller', ['action' => 'index']);
* $builder->connect('/:controller/:action/*', []);
* ```
*
* You can remove these routes once you've connected the
* routes you want in your application.
*/
$builder->fallbacks();
});