Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get response as json format(application/json) in yii?

Tags:

php

yii

How to get response as json format(application/json) in yii?

like image 726
tq0fqeu Avatar asked May 13 '10 06:05

tq0fqeu


5 Answers

For Yii 1:

Create this function in your (base) Controller:

/**
 * Return data to browser as JSON and end application.
 * @param array $data
 */
protected function renderJSON($data)
{
    header('Content-type: application/json');
    echo CJSON::encode($data);

    foreach (Yii::app()->log->routes as $route) {
        if($route instanceof CWebLogRoute) {
            $route->enabled = false; // disable any weblogroutes
        }
    }
    Yii::app()->end();
}

Then simply call at the end of your action:

$this->renderJSON($yourData);

For Yii 2:

Yii 2 has this functionality built-in, use the following code at the end of your controller action:

Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $data;
like image 58
marcovtwout Avatar answered Nov 03 '22 21:11

marcovtwout


$this->layout=false;
header('Content-type: application/json');
echo CJavaScript::jsonEncode($arr);
Yii::app()->end(); 
like image 39
Neil McGuigan Avatar answered Nov 03 '22 21:11

Neil McGuigan


For Yii2 inside a controller:

public function actionSomeAjax() {
    $returnData = ['someData' => 'I am data', 'someAnotherData' => 'I am another data'];

    $response = Yii::$app->response;
    $response->format = \yii\web\Response::FORMAT_JSON;
    $response->data = $returnData;

    return $response;
}
like image 20
Sergey Onishchenko Avatar answered Nov 03 '22 20:11

Sergey Onishchenko


$this->layout=false;
header('Content-type: application/json');
echo json_encode($arr);
Yii::app()->end(); 
like image 10
tq0fqeu Avatar answered Nov 03 '22 20:11

tq0fqeu


class JsonController extends CController {

    protected $jsonData;

    protected function beforeAction($action) {
        ob_clean(); // clear output buffer to avoid rendering anything else
        header('Content-type: application/json'); // set content type header as json
        return parent::beforeAction($action);
    }

    protected function afterAction($action) {
        parent::afterAction($action);
        exit(json_encode($this->jsonData)); // exit with rendering json data
    }

}

class ApiController extends JsonController {

    public function actionIndex() {
        $this->jsonData = array('test');
    }

}
like image 5
Andrii Mishchenko Avatar answered Nov 03 '22 21:11

Andrii Mishchenko