9

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.

user2959221
  • 295
  • 2
  • 4
  • 11
  • You could only do that, if you were to generate the content of your external JS resource dynamically - and that would be bad for caching. Having certain dynamic values output in a script block within the HTML is quite a common approach – if you don’t want that, then you could “collect” all those dynamic settings, and have just _one_ dynamically generated script resource that gets embedded before all other, static ones. (And use some kind of `config` object in that script, so that you don’t pollute the global namespace any more than necessary.) – CBroe May 09 '14 at 09:50

4 Answers4

8

For pass variable from php to js you can use

 Yii::$app->view->registerJs('var max = "'. $maxMinCost['max'].'"',  \yii\web\View::POS_HEAD);
Andrea Perdicchia
  • 2,786
  • 1
  • 20
  • 19
4

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.

Community
  • 1
  • 1
Box
  • 2,432
  • 1
  • 18
  • 20
4

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.

robsch
  • 9,358
  • 9
  • 63
  • 104
4

Since version 2.0.14, there is registerJsVar() available.

$this->registerJsVar ('modalTitle', Yii::t('app', 'Update details' ), View::POS_BEGIN);
FFurbo
  • 41
  • 3