There are two important steps:
1) Register the js file as follows:
$this->registerJsFile(Yii::$app->homeUrl . 'js/test.js', [JqueryAsset::className()]);
2) In an ajax request, you need to send the following value along with the data:
yii.getCsrfParam(): yii.getCsrfToken()
CSRF is a security feature that can be disabled in the controller, but is not recommended.
source share