Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 $this->registerJs($js); How to pass php variable inside the $js

Tags:

ajax

php

yii2

Below is my ajax script in my view.

$js = <<< JS
    $('.list-link').click(function(){
        $.ajax({
            url: '?r=public/getlist&param1=01&param2=02&param3=03',
            dataType: "json",
            success: function(data) {
                $(".well").html(data.id);                
            }
        })
    });
JS;
$this->registerJs($js);

Now my problem is how am I going to make the values of param1, param2 and param3 dynamic like I am going to pass the params1 to 3 from php variables.

like image 717
C. Norris Avatar asked Feb 01 '16 07:02

C. Norris


2 Answers

You could do it this way:

$url = \yii\helpers\Url::to([
    'public/getlist', 
    'param1' => '01', 
    'param2' => '02', 
    'param3' => '03'
]);

$js = <<< JS
    $('.list-link').click(function(){
        $.ajax({
            url: $url,
            dataType: "json",
            success: function(data) {
                $(".well").html(data.id);                
            }
        })
    });
JS;
$this->registerJs($js);

Of course you can make the number of parameters dynamic as well since it is just an array that gets passed to Url::to().

Official info about the used Heredoc (which allows variable usage) syntax can be found here.

like image 56
robsch Avatar answered Oct 15 '22 04:10

robsch


robsch's way is great (above answer).

But you can also do this way:

$js = <<< JS
    $('.list-link').click(function(){
        $.ajax({
            url: '?r=public/getlist&amp;param1=$one&amp;param2=$two&amp;param3=$three',
            dataType: "json",
            success: function(data) {
                $(".well").html(data.id);                
            }
        })
    });
JS;
$this->registerJs($js);

where $one, $two and $three are PHP variables.

And don't forgot to replace & with &amp; in Javascript text code string above in $js variable in PHP. It is less error prone and good practice too

like image 27
Sohel Ahmed Mesaniya Avatar answered Oct 15 '22 03:10

Sohel Ahmed Mesaniya