If you want that your method return data in specific format in Yii2 then you can use this simple construction:
Example method return in JSON format:
use yii\web\Response; //...... public function actionJson() { $something = true; // or you can set for test -> false; $return_json = ['status' => 'error']; if ($something == true) { $return_json = ['status' => 'success', 'message' => ' is successfully saved']; } \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return $return_json; } /*header results Connection: Keep-Alive Content-Length: 55 Content-Type : application/json; charset=UTF-8 */
Continue reading Yii 2 Response formats: RAW, HTML, JSON, JSONP, XML