After receiving an AJAX request, I want to give feedback to the user before the PHP script finishes, because it takes long.
I thought that the send()
method of the yii\web\Response
object was made for that, so I tried the following inside the controller action:
Yii::$app->response->format = Response::FORMAT_JSON;
Yii::$app->response->data = [ 'success' => $someData ];
Yii::$app->response->send();
// code that takes long
sleep(5);
The response is sent, but after sleeping for 5 seconds.
Same luck with:
ob_start();
echo json_encode([ 'success' => $someData ]);
header('Connection: close');
header('Content-Type: application/json');
header('Content-Length: '.ob_get_length());
ob_end_flush();
flush();
// code that takes long
sleep(5);
I didn't have any confidence in this last code working inside a controller action, but I had it in the first one... what am I missing?
EDIT: I'm using nginx + PHP_FPM