Chris De Rouck
Chris De Rouck

Reputation: 127

CakePHP 2.1 JsonView

I'm using the new CakePHP 2.1 and would like to use the JsonView to make my controller respond to an AJAX request created by jQuery on the client side.

However, this should be done automatically with the JsonView according to the documentation.

http://book.cakephp.org/2.0/en/views/json-and-xml-views.html

I added this line in my routes.php file

Router::parseExtensions('json');

And in my controller I have

$this->RequestHandler->setContent('json', 'application/json' ); 
$bookings = $this->Bookings->find('all');

$this->set('bookings', $bookings);  
$this->set('_serialize', 'bookings');

Then the view should be obsolete, but when I call this, it still serves a page which is pointing to a missing view.

Upvotes: 5

Views: 7360

Answers (3)

Gene Kelly
Gene Kelly

Reputation: 199

I had some issues with Cake wanting me to explicitly set the json view. The XML view loaded fine by default just not json.

I did the following in my API function:

    if($this->RequestHandler->ext == 'json') {
        $this->autoRender = false;
        echo json_encode($results);
    } else if($this->RequestHandler->ext == 'xml') {
        $this->set(array(
            'results' => $results,
            '_serialize' => array('results')
        ));
    }

Upvotes: 2

func0der
func0der

Reputation: 2232

Does the url you are calling ends on '.json'?

Upvotes: 5

James F
James F

Reputation: 346

Have you added the "RequestHandlerComponent" to your controller’s list of components?

I went the other route and created a JSON view: /app/View/Model/json/view.ctp

<?php
echo json_encode(array(
'success' => TRUE
));

And in my Controller I used:

$this->viewClass = 'Json';

Regards, James

Upvotes: 0

Related Questions