phpjsonyii2yii2-basic-app

Yii 2 set up controller to accept json requests


I'm quite new to Yii 2 but here goes:

What I'm trying to accomplish is to set up a controller that simply reads in any json data posted to it.

I'm slightly confused as to how this works in Yii.

What I've tried so far is set up a controller called ftest to see if I could get it returning some json which seems to work:

 public function actionFTest(){
    $request = Yii::$app->request;
    Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
    $headers = Yii::$app->response->headers;
    $headers->add('Content-Type', 'text/json');

    $response = Yii::$app->response;
    $response->format = \yii\web\Response::FORMAT_JSON;
    $response->data = ['message' => 'Evan .. WHERE ARE YOU?'];

    //$notificationData = json_decode(file_get_contents("php://input"), true);

    //echo var_dump($notificationData);

}

Its a bit messy since I've been throwing in code back and forth. I know I should usually return something like $this->render(etc), but I'm not sure what I need to return as a view.

Thanks for any help you can provide


Solution

  • This might be helpful

     use Yii;
        use yii\web\Response;
    
    
    
        public function actionFTest()
        {
              Yii::$app->response->format = Response::FORMAT_JSON;
        }
    
    Then after that just return a simple array like that:
    
        return ['param' => $value];
    

    Read this http://www.yiiframework.com/doc-2.0/yii-web-response.html#$format-detail