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.
I should get the autocomplete popup appear.
Nothing. The popup does not appear, since the response cannot be parsed correctly.
| 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.
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.
Most helpful comment
You should not echo response in controller, you should return it like: