M
M
MaikMain2021-02-20 16:21:47
Yii
MaikMain, 2021-02-20 16:21:47

Yii. How can php code be used when generating JS code?

Good afternoon. I have this code:

spoiler

$script = <<< JS
    $("#delete-select").on("click", function(e){
       e.preventDefault()
       var keys = $("#w0").yiiGridView("getSelectedRows");
       $.ajax({
         url: "\yii\helpers\Url::toRoute(['delete-select']).",
         type: "POST",
         data: {id: keys},
         success: function(){
            alert("yes")
         },
         error : function(){
            alert("Ошибка при отправке данных: перезагрузите страницу!");
          }
       })
   });
JS;
$this->registerJs($script, yii\web\View::POS_READY);



This code is not executed, and an error message is displayed in the console:

Access to XMLHttpRequest at 'yiihelpersurl::toRoute(['delete-select'])' from origin ' site.ru ' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome -extension, chrome-untrusted, https

Note that for some reason it "\yii\helpers\Url::toRoute(['delete-select'])", outputs as "yiihelpersurl::toRoute(['delete-select '])."


I wonder why it is displayed and how to fix it?
Thank you very much in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tim, 2021-02-20
@MaikMain

You are passing a string to a script. It will not generate a link there
More details - https://yiiframework.com.ua/en/doc/guide/2/output-...

$url = \yii\helpers\Url::toRoute(['delete-select']);
$script = <<< JS
    $("#delete-select").on("click", function(e){
       e.preventDefault()
       var keys = $("#w0").yiiGridView("getSelectedRows");
       $.ajax({
         url: "$url",
         type: "POST",
         data: {id: keys},
         success: function(){
            alert("yes")
         },
         error : function(){
            alert("Ошибка при отправке данных: перезагрузите страницу!");
          }
       })
   });
JS;
$this->registerJs($script, yii\web\View::POS_READY);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question