cakephpcakephp-2.0cakephp-2.2cakephp-2.3

Avoid creating a view for each AJAX function at CakePHP


I am trying to avoid creating a view for each AJAX function I am using at my controller. (as i don't manipulate the resulting data in any way and in most cases is just a boolean value)

I am using RequestHandler component at my controller:

var $components = array('RequestHandler');

And I added this in routes.php

Router::parseExtensions('json');

I am trying to make this function to work, but I am getting a null value:

public function test(){
    $this->layout = 'ajax';

    $result = '1';
    $this->set('_serialize', $result);
}

To access to the json version of the function i use this URL finishing in .json to avoid loading any view:

http://localhost/cakephp/demoController/test.json

I have been following the steps from CakePHP documentation: http://book.cakephp.org/2.0/en/views/json-and-xml-views.html#json-and-xml-views

What am I doing wrong? Why don't I get the expecting result and instead I get a null?

Also, if I try to to serialize some array, like this one:

$result = array('demo' => '1');
$this->set('_serialize', $result);

I'm getting this notice:

Notice (8): Undefined index: 1 [CORE\Cake\View\JsonView.php, line 89]Code Context                $data = array();                 foreach ($serialize as $key) {                     $data[$key] = $this->viewVars[$key];$view = null $layout = null $serialize = array( 'demo' => '1' ) $data = array() $key = '1'JsonView::render() - CORE\Cake\View\JsonView.php, line 89 Controller::render() - CORE\Cake\Controller\Controller.php, line 957 Dispatcher::_invoke() - CORE\Cake\Routing\Dispatcher.php, line 193 Dispatcher::dispatch() - CORE\Cake\Routing\Dispatcher.php, line 161 require - APP\webroot\index.php, line 92 [main] - ROOT\index.php, line 42{"1":null}


Solution

  • As far as I understand the documentation you have to specify a view variable and then refer to this variable when you use the _serialize key. This means your snippet would look like:

    $result = '1';
    $this->set('theResult', $result);
    $this->set('_serialize', array('theResult'));