February 6, 2016

PHP Yii2 Framework - How to use JavaScript

In order to use javascript with Yii2 framework, we have to register scripts with yii\web\view object. Yii2 provides two methods for it

  • registerJs() for inline scripts
  • registerJsFile() for external script files.

registerJs() for inline scripts

Here is an example to register an inline script.

$script = "function test() {console.log('a meesage logged in console.'); alert('Hello World');}";

$this->registerJs($script, View::POS_END, 'my-options');


  1. First argument is the script content itself
  2. Second argument determines the place in the page where the script should be inserted, e.g. Head, Begin, End, Load etc.
  3. And the last argument is used to uniquely identify the code block

Here is our test html to call this javascript test() function.

&input type="button" value="Click Me" onclick="test();"\>

registerJsFile() for external script files.

An external JavaScript file can be added with the method registerJsFile().


Registering with Asset Bundles

Another way to use JavaScript files in Yii2 framework is by registering it in asset bundles, and is preferred to use asset bundles instead of using JavaScript code/files directly You can use the following syntax to register current view for asset bundle.


With the following javascipt configuration block in AppAsset.php

public $js = [



No comments:

Post a Comment