Yii2: 2.0.16 broke JSON responses

Created on 6 Feb 2019  路  6Comments  路  Source: yiisoft/yii2

What steps will reproduce the problem?

Request content by json. For example, I use yii\jui\AutoComplete for a autocomplete box, but when I type, nothing happens, because I get a incorrent JSON response. I get the JSON object plus a null string at the end of it.

What is the expected result?

I should get the autocomplete popup appear.

What do you get instead?

Nothing. The popup does not appear, since the response cannot be parsed correctly.

Additional info

| Q | A
| ---------------- | ---
| Yii version | 2.0.16
| PHP version | 7.2.14
| Operating system |Linux

This is related to issue #17094 with response http status 204. This issue is for http response 200 (it has content). Downgrading to 2.0.15.1 fixes the issue.

Most helpful comment

You should not echo response in controller, you should return it like:

$result = Yii::$app->db->createCommand($query)
    ->bindValue(':afm', $term . '%', \PDO::PARAM_STR)
    ->queryAll();
return $this->asJson($result);

All 6 comments

How do you generate this JSON response?

With something like this:

$result = Yii::$app->db->createCommand($query)
    ->bindValue(':afm', $term . '%', \PDO::PARAM_STR)
    ->queryAll();
Yii::$app->response->format = Response::FORMAT_JSON;
echo Json::encode($result);
Yii::$app->end();

in the controller action.

You should not echo response in controller, you should return it like:

$result = Yii::$app->db->createCommand($query)
    ->bindValue(':afm', $term . '%', \PDO::PARAM_STR)
    ->queryAll();
return $this->asJson($result);

Ok, I didn't know that one. Yes, it works fine. Thanks! Sorry for the noise.

If you still want to __end__ the app,you can change the code
from

...
Yii::$app->response->format = Response::FORMAT_JSON;
echo Json::encode($result);
Yii::$app->end();

to

...
$this->asJson($result);
Yii::$app->end();

@j0hnh that will not send the Response. The correct way is to return the Response object and let yii finish the request response-workflow.

Was this page helpful?
0 / 5 - 0 ratings