PHP CAKE 5, ajax call

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 found where the change was: 4.4 Migration Guide - 4.x

can you show the full code? I am stuck in ajax in CakePHP 5

Code of what exactly?

I am still getting an error Template missing.

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:

// webroot/js/ajax.js

fetch('/tmp/ajax', {
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
        .then(r => r.json())
        .then(d => console.log(d));

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).

https://book.cakephp.org/5/en/views/json-and-xml-views.html#json-and-xml-views

1 Like

Thanks, I will check it today.