Below is my ajax script in my view.
$js = <<< JS
$('.list-link').click(function(){
$.ajax({
url: '?r=public/getlist¶m1=01¶m2=02¶m3=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.
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.
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&param1=$one&param2=$two&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&
in Javascript text code string above in$js
variable in PHP. It is less error prone and good practice too
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With