Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp 3 : Json render View not working

I've been trying to setup an Ajax Call in Cakephp 3.0.11. I've followed the explanation here : http://book.cakephp.org/3.0/en/views/json-and-xml-views.html

Json enabled in routing (but i'm not really sure that's usefull) :

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

I've setup my exemple in controller :

$returnObject = new ObjectReturn();
$this->set('returnObject', $returnObject);
$this->set('_serialize', ['returnObject']);

But when I make my ajax call, I've got :

{
    "message": "Template file \Pages\\score.ctp\ is missing.",
    "url": "\/pages\/score",
    "code": 500
}

If I create the page, he juste render me some html, with default.ctp as a layout. What's wrong here ?

Thanks a lot !

like image 912
Gael.D Avatar asked Dec 02 '22 16:12

Gael.D


1 Answers

If you'd like to force every response (except errors) to JSON (and skip templates) you can put this code in your AppController.php

public function initialize()
{
    parent::initialize();
    $this->loadComponent('RequestHandler');
}

public function beforeRender(Event $event)
{
    $this->RequestHandler->renderAs($this, 'json');
    $this->response->type('application/json');
    $this->set('_serialize', true);
}

This loads the RequestHandlerComponent, forces the render to JSON, forces the response type to JSON, and skips using templates.

More in the manual here: http://book.cakephp.org/3.0/en/controllers/components/request-handling.html

like image 76
Steve Tauber Avatar answered Dec 06 '22 10:12

Steve Tauber