Simple AJAX in CakePHP 4.0.3

Dear all,

I have a WardsController with actions like below

public function initialize(): void {

public function getWards($districtID) {

    $query = $this->Wards->find('list')
            ->where(['district_id' => $districtID]);
    $wardList = $query->toArray();

    $this->set('wardsList', $wardList);
    $this->viewBuilder()->setOption('serialize', ['wardsList']);
    //$this->set('_serialize', array('wardsList'));

I have enabled the extensions in config/Route like below:

   $routes->scope('/', function (RouteBuilder $builder) {
      // Register scoped middleware for in scopes.
      $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
          'httpOnly' => true,

      $builder->setExtensions(['json', 'xml']);

When I connect to /wards/get-wards.json/1 i get missing method in controller.
If I leave the .json out of the url, then missing view class error returned.

Did I miss something? Thanks very much.

It’s /controller/action/id and add .json to that if you want a json answer. So instead of /wardsget-wards.json/1 try /wards/get-wards/1.json.

1 Like

wow, thank you very much, it works.