5

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.

jDo
  • 3,962
  • 1
  • 11
  • 30
Chris De Rouck
  • 127
  • 2
  • 5

3 Answers3

5

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

func0der
  • 2,192
  • 1
  • 19
  • 29
  • 1
    This makes indeed the difference! Thanks. A bit strange that the .json is required for this in a framework that supports url rewriting for seo... – Chris De Rouck Mar 26 '12 at 20:39
  • 2
    no problem. But this is of course a good thing. So you perfectly know what call to your page was an ajax call and which not (e.g. in awstats or similar). To not fall over such problems in the future try to have a look in the core code of cake. Following a request from getting in the framework until getting in the action in a controller by dumping vars or reflecting classes shows you a lot about the framework itself. ;) But you could ask again, also ;P – func0der Mar 27 '12 at 18:28
2

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')
        ));
    }
Gene Kelly
  • 189
  • 9
0

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

James F
  • 346
  • 2
  • 8
  • Might work, but I was searching for the "easy" solution with the JsonView, the answer below makes an extra view obsolete... – Chris De Rouck Mar 26 '12 at 20:41