Hello there,
I’m trying to use the Ajax plugin (dereuromark/cakephp-ajax). I’ve CakePHP 4.4.12 running and set up the plugin as mentioned in readme. When I make my Ajax call, I receive a json-formatted response which contains the keys “error”, “success” and “content”. The value of “error” is a html error page telling me, the template [controllername]/ajax/index.php is missing. But as I’m using the AjaxComponent such a template should not be necessary.
I would expect, that a json-response would automatically be created and returned if it is an Ajax request, otherwise, the “normal” view would be rendered.
Can sb. help me / give me advice?
Actual response:
{
"error": {
"xdebug_message": "<tr><th align='left' bgcolor='#f57900' colspan=\"5\"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Cake\\View\\Exception\\MissingTemplateException: Template file `Articles/ajax/index.php` could not be found.\n\nThe following paths were searched:\n............"
}
"content": null
"success": false
routes.php
$routes->scope('/', function (RouteBuilder $routes) {
Router::extensions(['json']);
...
}
Application.php
public function bootstrap(): void
{
// Call parent to load bootstrap from files.
parent::bootstrap();
$this->addPlugin('Ajax', ['bootstrap' => true]);
AppController.php
public function initialize(): void
{
parent::initialize();
$this->loadComponent('Ajax.Ajax');
}
public function beforeRender(\Cake\Event\EventInterface $event)
{
parent::beforeRender($event);
if ($this->request->is('ajax')) {
$this->viewBuilder()->setClassName('Ajax.Ajax');
}
}
A Controller
public function viewClasses(): array {
if (!$this->request->getParam('_ext')) {
return [];
}
return [JsonView::class];
}
public function index()
{
$this->request->allowMethod(['ajax', 'get']);
$data = $this->paginate($this->Articles);
//From sandbox "simple.php" (dereuromark)
if ($this->request->is(['ajax'])) {
// Lets create current datetime
$now = date("d-m-Y-H-i-s");
$this->set('result', ['now' => $now]);
$this->set('_serialize', ['result']);
}
else
{
$this->set(compact('data'));
$this->set('_serialize', ['data']);
}
}
view
function ajaxTest()
{
$.ajax({
url: '/articles/index.json',
method: 'get',
dataType: 'json',
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
alert(error);
}
});
}
Thanks in advance.