I followed this tutorial to set up my REST webservice for JSON and XML. XML outputs properly but when I make a JSON call I get the view not found display from Cake.
To do this I added the following code in my AppController:
if ( $this->RequestHandler->isAjax() ) {
//Configure::write ( 'debug', 0 );
$this->layout = 'ajax';
$this->autoRender = false;
} elseif ($this->RequestHandler->isXml()) {
$this->layout = 'default';
//Configure::write ( 'debug', 0 );
} elseif ($this->RequestHandler->ext == 'json') {
$this->RequestHandler->setContent('json','text/x-json');
$this->layout = 'default';
} elseif ($this->RequestHandler->accepts('html')) {
$this->layout = 'frontend';
}
And this is an example of the code in one of my controller methods:
if ($this->RequestHandler->isXml()) {
$voicenote = $voicenote['Voicenote'];
$this->set(compact('voicenote'));
} else if ($this->RequestHandler->ext == 'json') {
$voicenote = $voicenote['Voicenote'];
pr($voicenote);
echo json_encode(array('voicenote' => $voicenote));
} else {
$this->set(compact('voicenote', 'tiny_list'));
}
XML displays properly, it’s just JSON that’s the issue.
The issue is that auto-render is only being disabled if the request is performed via an AJAX request.
When entering the address in a browser address bar, after the
echo json_encode();call, the controller will continue on in the render pipeline, looking for an action and layout template to output.I would suggest being consistent between your XML and JSON rendering, and output both through template files and not disable autoRender for AJAX requests.
AppController:
Your controller only needs to set the data, and each view template will format it as necessary:
The JSON templates will be relatively simple, create as required by the error messages.
Layout:
JSON Action (app/views/controller/json/action.ctp)
Check out the CakePHP RequestHandler documentation for more help