My Google+ Profile

Wednesday 13 March 2013

Yii – adding JavaScript into your views using Controller

We can use Yii’s CClientScript for add javascript.
//in your view where you want to include JavaScripts  
Add following line of code in your controller action :  
$cs = Yii::app()->getClientScript();  
$cs->registerScript(
  'my-hello-world-1',
  'var popup = "Hello" + " " + "World";
  alert(popup);',
  CClientScript::POS_END
);
In the example above, the first argument is an ID uniquely identifies the script, the second is the actual JavaScript. The third argument determinds where the JavaScript will be inserted into the view – by using CClientScript::POS_END the script will be inserted at the before the closing of the body tag.

If you wish to include a JavaScript file instead, we can use registerScriptFile.
First, we place our JavaScript into protected/components/js folder.

Add following line in  controller  action.
Yii::app()->clientScript->registerScriptFile(
        Yii::app()->baseUrl . '/components/js/myScript.js',
 CClientScript::POS_END
 );

No comments:

Post a Comment