Yii2. How to pass data via ajax?

All kind time of day.
Deal with a question how to pass data from view to controller using ajax.
Here's what I get:
In the view there is JS code:
<?php
$js=<<<JS
 $("#testBut").on("click", function(e) {
$ajax({
 url : '/analytica',
 type : 'POST',
 data : {dat : 'qwe', '<?= Yii::$app--->request->csrfParam; ?>' : '<?= Yii::$app--->request->getCsrfToken() ?>'},
 success : function(res){
console.log(res);
},
 error : function(){
 alert('Error sending data: reload the page!');
}
})
 return false;
})
JS;
$this->registerJs($js);
?>


In the controller the following code:
public function actionIndex()
{
if(\Yii::$app->request->isAjax){
 return 'Request';
}
 return $this->render('index');
 }


On the Internet subtracted that the data may not be sent due to the fact that I don't pass csrf, which is why in the JS code added
'<?= Yii::$app--->request->csrfParam; ?>' : '<?= Yii::$app--->request->getCsrfToken() ?>'


But since the code is not converted and is displayed right as written - I understand that somewhere took a wrong turn.

I would be grateful if you can tell what direction to move further
June 14th 19 at 21:00
1 answer
June 14th 19 at 21:02
Solution
The issue was resolved very simply
$this->registerJs('$("#testBut").on("click", function(e) {
$.ajax({
 url: "'.\yii\helpers\Url::toRoute([",'id'=>$someid]).'",
 type : "POST",
 data : {dat : "qwe"},
 success : function(res){
console.log(res);
},
 error : function(){
 alert("Error sending data: reload the page!");
}
})
 return false; 
 })');


Anyone can tell how can I use php code in the formation of the JS code this way:

$js=<<<js ... js; $this->registerJs($js);</js>

Find more questions by tags AJAX