David David - 4 months ago 32
Ajax Question

How to continue a script after AJAX response is sent to user in Yii2?

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

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

Answer

PHP_FPM has fastcgi-finish-request() available:

This function flushes all response data to the client and finishes the request. This allows for time consuming tasks to be performed without leaving the connection to the client open.

Yii::$app->response->format = Response::FORMAT_JSON;
Yii::$app->response->data = [ 'success' => $someData ];
Yii::$app->response->send();

fastcgi-finish-request();

// code that takes long
sleep(5);
Comments