Rugleh Rugleh - 7 days ago 6
PHP Question

Parse a PHP array in a JS file with a JS variable inside the PHP parsed array -YII2

How should I do this?

$ids = ArrayHelper::map(Tours::find()->select(['pk', 'programa'])->asArray()->all(), 'pk', 'programa');


$this->registerJs('
$("#child1_child2").change(function() {
var val = $("#child1_child2 option:selected").val();
valInt = parseInt(val);
$("#form").attr("action", "programas/" + "'.$ids[.'"valInt"'.].'");
});
', \yii\web\View::POS_END);


I dont know how to parse this part:

$("#form").attr("action", "programas/" + "'.$ids[.'"valInt"'.].'");


$ids it's a php array

valInt is a js varibale

I thought this was correct but I'm getting parse error

syntax error, unexpected '.', expecting ']'


if I write
"'.$ids[40].'"
it works great and with no errors.

Thi is in the view of site/index.php, working with Yii2.

Thanks for the help!

Answer

Try this

$ids = ArrayHelper::map(Tours::find()->select(['pk', 'programa'])->asArray()->all(), 'pk', 'programa');


$this->registerJs('
$("#child1_child2").change(function() {
    var val = $("#child1_child2 option:selected").val();
    valInt = parseInt(val);
    var $ids = '. json_encode($ids) .';
    $("#form").attr("action", "programas/" + $ids[valInt]);
});
', \yii\web\View::POS_END);