Answer the question
In order to leave comments, you need to log in
Yii2. How to send data via ajax?
Good day to all.
I'm trying to figure out how to pass data from a view to a controller using ajax.
Here's what I get:
There is JS code in the view:
<?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('Ошибка при отправке данных: перезагрузите страницу!');
}
})
return false;
})
JS;
$this->registerJs($js);
?>
public function actionIndex()
{
if(\Yii::$app->request->isAjax){
return 'Запрос принят';
}
return $this->render('index');
}
'<?= Yii::$app->request->csrfParam; ?>' : '<?= Yii::$app->request->getCsrfToken() ?>'
Answer the question
In order to leave comments, you need to log in
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("Ошибка при отправке данных: перезагрузите страницу!");
}
})
return false;
})');
$js=<<<JS
...
JS;
$this->registerJs($js);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question