Is there a change in PHP CAKE 5, if I call ajax - then the template default.php and not ajax.php is loaded automatically?
If I put this in AppController.php
public function beforeFilter(EventInterface $event)
{
parent::beforeFilter($event);
if ($this->request->is('ajax')) {
$this->viewBuilder()->setLayout('ajax');
}
}
it works correctly. It worked automatically in PHP CAKE 4.x, any advice?
I have found that in order to trigger the $this->request->is('ajax') detection and load the AjaxView class you need to set an X-Requested-With header when fetching with javascript:
Then in the controller action you can set AjaxView as the class.
// src/Controller/TmpController.php
public function ajax()
{
if ($this->request->is('ajax')) {
$this->viewBuilder()->setClassName('Ajax');
// you need to set an ajax template
$this->viewBuilder()->setTemplate('ajax/ajax');
} else {
// for non ajax just use a normal html template
$this->viewBuilder()->setTemplate('index');
}
$data = json_encode(['hi' => 'james']);
$this->set(compact('data'));
}
For the above action the ajax view file is as follows. I put it in a subdirectory so it’s clear it is an ajax view.
// templates/Tmp/ajax/ajax.php
<?= $data; ?>
If you are doing Json and don’t need to massage it then using JsonView and serialize etc is a bit easier. But you probably still need to set a header in ajax requests so it auto detects correctly and returns the correct content encoding (application/json).