Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a php variable to JavaScript external file in YII2

Tags:

php

yii2

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.

like image 881
user2959221 Avatar asked May 09 '14 09:05

user2959221


4 Answers

For pass variable from php to js you can use

 Yii::$app->view->registerJs('var max = "'. $maxMinCost['max'].'"',  \yii\web\View::POS_HEAD);
like image 155
Andrea Perdicchia Avatar answered Oct 12 '22 20:10

Andrea Perdicchia


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.

like image 39
robsch Avatar answered Oct 12 '22 21:10

robsch


Since version 2.0.14, there is registerJsVar() available.

$this->registerJsVar ('modalTitle', Yii::t('app', 'Update details' ), View::POS_BEGIN);
like image 40
FFurbo Avatar answered Oct 12 '22 20:10

FFurbo


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.

like image 28
Box Avatar answered Oct 12 '22 19:10

Box