Get response in JSON format in Yii2
Set
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
in the controller's action somewhere before return
.
Since Yii 2.0.11 there is a dedicated asJson()
method to return a response in JSON format. Run:
return $this->asJson($array);
in your controller action.
Simply Add this in controller
public function beforeAction($action)
{
\Yii::$app->response->format = Response::FORMAT_JSON;
return parent::beforeAction($action);
}