CakePHP - Just Layout? CakePHP - Just Layout? json json

CakePHP - Just Layout?


@pleasedontbelong's solution works. You can also create a layout and view for ajax.

Your layout can be something like this:

<?php echo $content_for_layout;?>

And then you can create an ajax view like this:

<?php echo $this->Js->object($result);?>

And then from your controller...

public function savecontent(){    $this->autoRender = false;    $this->set('result', false);    if(!empty($this->data)){        $data = $this->data;        //Do something with your data        //send results to view        $this->set('result', $myNewData);    }    $this->render(null, 'ajax','/ajax/ajax');}


hmmm it should be something like this: (not tested)

function action(){    $this->autoLayout = $this->autoRender = false;     // your code    $this->render('/layouts/json');}

Hope this helps


In config/routes.php:

Router::parseExtensions('json');

In app_controller.php:

var $components = array('RequestHandler');var $helpers = array('Js');function render($action = null, $layout = null, $file = null) {    switch($this->RequestHandler->ext) {        case 'json':            Configure::write('debug', 0);            return parent::render(null, 'default', '/json');        default:            return parent::render($action, $layout, $file);    }}

In views/json.ctp:

<?php echo $this->Js->object(isset($data) ? $data : array()); ?>

In views/layouts/json/default.ctp:

<?phpheader('Cache-Control: no-store, no-cache, max-age=0, must-revalidate');header('Content-Type: application/json');echo $content_for_layout;?>

In the controller action you want to output json:

$this->set('data', array('foo' => 'bar'));

Now every call to an action with the .json extension (www.example.com/posts/view/12.json) will output a json object without having to call the render function in each action.