Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP - How to return string (like JSON) from controller action to 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 output something back to the JavaScript.

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

like image 310
BadHorsie Avatar asked Dec 05 '22 20:12

BadHorsie


2 Answers

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

General 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); ?>
like image 111
Saad Imran. Avatar answered Dec 07 '22 23:12

Saad Imran.


Easiest way I found was to disable the 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'));
    }   
}
like image 29
Shaz Amjad Avatar answered Dec 07 '22 23:12

Shaz Amjad