CakePHP3 path to template file error on json calls

264 Views Asked by At

I've just converted an ajax call to return json instead of HTML.

If I

  • make the request manually or via postman I get the expected result.
  • call from my site using ajax I get an error.
  • use devtools/Network to open in new tab I get the expected result.

Why is cake processing it differently?

Why is it adding the extra /json to the template path?

code: 500
file: "Forms/json/json/get_more.ctp"
line: 1092
message: "Template file "Forms/json/json/get_more.ctp" is missing."
url: "/forms/getMore/60498/0/6?_=1599996955252"

Adding .json to the URL makes no difference.

I've added to routes.php $routes->extensions(['json', 'xml', 'html']);

I need to use a template in order to get my helper to process some data so I have $this->set('_serialize', false);

2

There are 2 best solutions below

0
On

Make sure you have added the code in routes.php

$routes->extensions(['json']);

inside the the function

Router::scope('/', function (RouteBuilder $routes) {

Now, in controller assuming $responseArray is the response you want in json you have to write the below lines at the end of the action.

$this->set('responseRoot', $responseArray);
$this->set('_serialize', array('responseRoot'));

Delete the ctp file, they are not required for .json type requests unless you want a specific type of formatting.

0
On

if you use the method ajax of jquery, remove the param dataType

//  dataType: 'json',