This might be repeated questions, but I have tried all possible methods to resolve this error in Yii2 without any success
I have my base controller and function as written below in it
/**
* Send given object as json object
*
* @param array $data
* @return json
*/
public function sendJsonResponse($data) {
ob_start();
ob_clean();
header('Content-type: application/json');
echo json_encode($data);
die;
}
I call this function in any of the child controllers like
return $this->sendJsonResponse(['message'=>'Some message here','status'=>true]);
With this I get headers already sent error all the time, tried ways suggested by Yii2 community to change echo to return etc. but in vain.
Please suggest.
@ScaisEdge, thank you for your answer, for some weird reasons, your suggested method does not yield expected results whenever we are using ajax, not sure why so modified my method as given below
/**
* Send given object as json object
*
* @param array $data
* @return json
*/
public function sendJsonResponse($data) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $data;
}
This is working as expected, I will post confirmation on whether this resolves the headeralreadysent error that I was originally getting.