How to return JSON from CakePHP 2.2 controller?

I call the controller function:

$.get("http://localhost/universityapp/courses/listnames", function(data){ alert("Data Loaded: " + data); }); 

And in my controller:

 public function listnames() { $data = Array( "name" => "Sergio", "age" => 23 ); $this->set('test', $data); $this->render('/Elements/ajaxreturn'); // This View is declared at /Elements/ajaxreturn.ctp } 

And in this view:

 <?php echo json_encode($asdf); ?> 

However, the action returns the entire page, including the contents of the layout (title, footer, navigation).

What am I missing here? How can I return only JSON data without layout content?

+6
source share
4 answers

You need to disable the layout like this

 $this->layout = null ; 

Now your action will become

 public function listnames() { $this->layout = null ; $data = Array( "name" => "Sergio", "age" => 23 ); $this->set('test', $data); $this->render('/Elements/ajaxreturn'); // This View is declared at /Elements/ajaxreturn.ctp } 
+10
source

Set autoRender=false and return json_encode($code) : -

 public function returningJsonData($estado_id){ $this->autoRender = false; return json_encode($this->ModelBla->find('first',array( 'conditions'=>array('Bla.bla_child_id'=>$estado_id) ))); } 
+24
source

Learn about JsonView in the manual.

+7
source

You can try any of the following to return a json response (I received a failure case to return a json response):

 public function action() { $this->response->body(json_encode(array( 'success' => 0, 'message' => 'Invalid request.' ))); $this->response->send(); $this->_stop(); } 

OR

 public function action() { $this->layout = false; $this->autoRender = false; return json_encode(array( 'success' => 0, 'message' => 'Invalid request.' )); } 
+1
source

Source: https://habr.com/ru/post/928066/


All Articles