How to return JSON from a CakePHP 2.2 controller?
Asked Answered
A

4

9

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?

Andria answered 18/10, 2012 at 20:7 Comment(4)
set $this->layout = null ; in listnames – Upsurge
@MoyedAnsari: If you write that in as your answer I'll accept it as the solution. – Andria
answer posted hope this will work for u – Upsurge
Be sure to $this->response->type('json'); too πŸ˜€ – Lager
U
10

You need to disable 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
}
Upsurge answered 18/10, 2012 at 20:15 Comment(0)
T
32

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)
    )));
}
Twylatwyman answered 10/7, 2014 at 20:43 Comment(1)
+1 The simpliest solution for this simple situation. – Kharif
U
10

You need to disable 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
}
Upsurge answered 18/10, 2012 at 20:15 Comment(0)
K
7

Read up about JsonView on the manual.

Kovrov answered 19/10, 2012 at 6:5 Comment(0)
D
1

You can try any of the following to return json response (I've taken failure case here to return 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.'
    ));
}
Daffi answered 24/6, 2015 at 11:50 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.