Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return JSON from a CakePHP 2.2 controller?

I'm invoking a 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 that View:

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

However, the Action is returning the entire page including the Layout content (header, footer, navigation).

What am I missing here? How can I return just the JSON data without the Layout content?

like image 873
sergserg Avatar asked Oct 18 '12 20:10

sergserg


1 Answers

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)
    )));
}
like image 141
Guilherme Ferreira Avatar answered Oct 02 '22 21:10

Guilherme Ferreira