How do I return JSON in a DooPHP Controller?

1k Views Asked by At

I'm setting up an AJAX system and I have a controller that I need to return JSON data. In the examples so far, all of the controllers end with a call to the view:

    $this->renderc( 'interest', $data );

I'd like to return straight JSON for use with jQuery, but the code below is not quite working right:

return json_encode($data);

because the return comes through as the header, not the content in Firebug. Heeeelp!

2

There are 2 best solutions below

0
On BEST ANSWER

Documentation:

Some times it is great to add extension at the end of a URL (great for REST api). If you need to do so, simply add the extension name in your routes:

$route['*']['/simple.rss'] = array('FeedController', 'getRss');
$route['*']['/simple.atom'] = array('FeedController', 'getAtom');

It is a bit different if you want to have add it to a route with parameters:

$route['*']['/news/list/:id'] = array('FeedController',
                                      'listNews',
                                      'extension'=>'.json'
                                     );

//Or multiple extension names.
$route['*']['/news/list/:id'] = array('FeedController',
                                      'listNews',
                                      'extension'=>array('.json', '.xml')
                                     );

Users can access it via http://domain/news/list/168.json OR 168.xml

0
On

to out out the data in JSON format (with appropriate content type headers of course) Use this in controller. $this->toJSON($data, true);