1

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!

Mat
  • 202,337
  • 40
  • 393
  • 406
Shamoon
  • 41,293
  • 91
  • 306
  • 570

2 Answers2

2

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

Dalen
  • 8,856
  • 4
  • 47
  • 52
0

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

user725840
  • 261
  • 2
  • 4