I've been trying to pass a php variable's value to JavaScript. I can do it when the js code put in the same php view file. but I'dont want to put js code inside the php because its become very tedious to debug or further development.
$this->registerJsFile('/js/myJs.js', [JqueryAsset::className()]);
please help.
For pass variable from php to js you can use
Yii::$app->view->registerJs('var max = "'. $maxMinCost['max'].'"', \yii\web\View::POS_HEAD);
Another option (compared to pass data with registerJs
) would be to add some data
attributes to your HTML elements. Quite often this makes sense when an certain element represents a certain corresponding thing. Example:
<table>
<?php foreach($items as $item) { ?>
<tr data-item-id="<?= $item->id ?>">
<td>something...</td>
</tr>
<?php } ?>
</table>
Then you can have the JS code in a seperate (not generated) file.
Some documentation for data
attributes and usage can be found in MDN.
Since version 2.0.14, there is registerJsVar() available.
$this->registerJsVar ('modalTitle', Yii::t('app', 'Update details' ), View::POS_BEGIN);
Use an inline JS script before using the external JS script.
$inlineScript = 'var key = ' . $value . ';';
$this->registerJs($inlineScript, View::POS_HEAD, 'my-inline-js');
$this->registerJsFile('/js/myJs.js', [
'depends' => [...],
'position' => View::POS_BEGIN);
The position constants are used to make sure the JS variable, such as "key" in the above case is defined before the external script.
There are other ways to pass PHP variables to external JS scripts, such as Ajax. Please refer to "How to pass variables and data from PHP to JavaScript?" for more detail.
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