A
A
Alexander Tokarchuk2017-10-01 21:30:15
Yii
Alexander Tokarchuk, 2017-10-01 21:30:15

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);
?>


In the controller, the following code:
public function actionIndex()
    {
    	if(\Yii::$app->request->isAjax){
      return 'Запрос принят';
    }
        return $this->render('index');
    }


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


But since the code is not converted, but is displayed exactly as it is written - I understand that somewhere I turned the wrong way.

I'd be grateful if you could give me some direction on how to proceed.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2017-10-01
@Kewa2008

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;  
      })');

Can anyone tell me how to use php code when generating JS code in this way:
$js=<<<JS
...
JS;
$this->registerJs($js);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question