Andy
Andy

Reputation: 5404

CakePHP 2.x not producing json response

I have a Cake 2.x application. I need to provide a JSON encoded response from a PHP array, but it's not working as expected.

In app/Config/routes.php I have Router::parseExtensions('json');

In my Controller I have this code:

public function ajaxTags()
{
    $this->loadModel('Tag');
    $tags = $this->Tag->find('list');
    var_dump($tags);
    die;
}

This produces what I expect - a PHP array of data in my 'tags' database table, e.g.

array(4) { 
    [1]=> string(14) "United Kingdom"
    [2]=> string(6) "France"
    [3]=> string(7) ... 
}

So all I want to do is get this as JSON encoded data. I've followed the instructions at https://book.cakephp.org/2.0/en/views/json-and-xml-views.html

So at the top of my TagsController.php I have:

public $components = array('RequestHandler');

And then I try and output it using _serialize as stated in the docs. I don't need a "view" for this because I don't want to do any additional formatting:

public function ajaxTags()
{
    $this->loadModel('Tag');
    $tags = $this->Tag->find('list');
    $this->set('_serialize', array($tags));
}

This gives the following response:

null

The response data is encoded as Content-Type:application/json; charset=UTF-8 (I can see this in my browser Network tab).

Where am I going wrong? I know that $tags has data in it because I var_dump'd it earlier. Why is it giving a null output now?

Upvotes: 2

Views: 1002

Answers (1)

SamHecquet
SamHecquet

Reputation: 1836

Based on the documentation, your action should be like this:

public function ajaxTags()
{
    $this->loadModel('Tag');
    $tags = $this->Tag->find('list');
    $this->set('tags', $tags);
    $this->set('_serialize', array('tags'));
}

The _serialize key is a special view variable that indicates which other view variable(s) should be serialized when using a data view.

You need to send the variable $tags to the view so the _serialize key will know it and will render it.

Upvotes: 2

Related Questions