Search code examples
jsondebuggingcakephpdataviewrequesthandler

How do I test the output of a JSON data view in CakePHP?


So I am trying to create an Android mobile application and I am using CakePHP as my serverside. I will not be needing any HTML views, I will only be responding with JSON objects.

I have taken a look at http://book.cakephp.org/2.0/en/core-libraries/components/request-handling.html#RequestHandlerComponent and with that I've created this:

class LocationsController extends AppController
{
    public $helpers = array('Html', 'Form');
    public $components = array('RequestHandler');
    function index()
    {
        $locations = $this->Location->getNearest();
        $this->set(compact('locations'));
        $this->set('_serialize', array('locations'));
    }
}

and I have added this to my routes.php:

Router::mapResources('locations');
Router::parseExtensions('json');

Nothing is displayed when I run this apart from the default CakePHP layout style. If I remove the index.ctp view file, I get an error that it can't find the view file. Why does it still require a view file? I thought with the serialize approach it does not need a view. I have tried looking in the Google Chrome developer console and there is no response that contains the JSON object. However, the MySQL has performed perfectly fine.


Solution

  • Put $this->render(false); between

    public $components = array('RequestHandler');
    

    and

    function index()
    

    Now it doesn't require an index.ctp file anymore.

    See this link for more information.