How to execute code after returning view in Yii2

Normally when you call a page in Yii2, pretty much the last thing that happens is that the view is rendered to the end user’s screen. I need to run code after this that might take a second or two and I don’t want to have the user wait.

My first thought was to set a global event that gets called after the response is set so I added this to a method:

if (condition is met) {
    Yii::$app->on(yii\web\Response::EVENT_AFTER_SEND, function ($event) {
        // do stuff
    });
}

But this doesn’t seem to ever get called. Does anyone know what I’m doing wrong or have a better idea on how to solve this problem? I just need to run code after the view is rendered. I don’t really care how it happens.

After view is rendered to the user you can only run JavaScript.
If you use JQuery then do something like this in the view you are rendering

$script = <<< JS
$('document').ready(function(){
    //Your JavaScript Code here when page is loaded
});
JS;

$this->registerJs($script, \yii\web\View::POS_END);

for communicating to Yii backend, use AJAX

Thanks but unfortunately it needs to be without javascript/JQuery/AJAX. Server-side only.

Impossible to do when the page have rendered!
Check if After action event is useful for your case!

I just tried this.
Can be done by config

		'response' => [
			'class' => 'yii\web\Response',
			'on afterSend' => function ($event) {
				Yii::debug('after send');
			},
		],
 
1 Like

If you need to call method after rendering the view, you may also use View::EVENT_END_PAGE.