CakePHP - How to return a string (e.g. JSON) from a controller action in an Ajax request

So, I have my JavaScript making an Ajax call to /my_controller/ajax_action , but then in the controller I don't know what to do to bring something back to JavaScript.

I get errors because there is no view for MyController::ajaxAction() , but obviously there is no view for it, so what am I doing?

+4
source share
4 answers

do this, specify the variables that you want to display in the array, say $data , then pass this array to the view using the $this->set('data', $data); method $this->set('data', $data); and then create the view /General/SerializeJson.ctp . In this view file, put <?PHP echo json_encode($data); ?> <?PHP echo json_encode($data); ?> after that, you can use $this->render('/General/SerializeJson'); and it should output json.

Common code ...

/Controllers/MyController.php

 public class MyController extends AppController { public function ajaxAction() { $data = Array( "name" => "Saad Imran", "age" => 19 ); $this->set('data', $data); $this->render('/General/SerializeJson/'); } } 

/Views/General/SerializeJson.ctp

 <?PHP echo json_encode($data); ?> 
+8
source

The easiest way I've found is to turn off automatic rendering:

 function ajax_action($data = null) { if($this->RequestHandler->isAjax()) { $this->autoRender = false; //process my data and return it return $data; } else { $this->Session->setFlash(__('Not an AJAX Query', true)); $this->redirect(array('action' => 'index')); } } 
+4
source

try the following:

in your view folder for the corresponding controller (my_controller) create a folder named json and put a file called index.ctp and inside this ctp file write this code:

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

in your my_controller in index() wrote this code:

 $this->set('yourVariableNameReturnedFromController', $this->YOURMODEL->find('all')); 

inside your app_controller.php (if it doesn’t exist, you have to do it) write this code

 function beforeFilter(){ if ($this->RequestHandler->ext == 'json') { Configure::write('debug', 0); } } 
+3
source

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) ))); } 
+1
source

All Articles