Passing variables from PHP (Server-side) to Javascript (Client-side) in Yii.

There are many occasions on which we need to pass some php variables to javascirpt, like application’s base-url as base path for Ajax requests or Application’s information.

We need to embed php code lines in js, wherever we need some php variable value.

<script type=”text/javascript”>
var applicationBasePath='<?php echo Yii::app()->request->baseUrl; ?>’;
// Some javascript code using applicationBasePath

If we want to keep js code in javascript files only, instead of embedding php code in javascript.

I think, what better we can do is that, we can create global js variables at one place and use in any javascript code on the page.

$clientScript->registerScript(‘MyApplication’,’var MyApplication=’.CJSON::encode(array(‘baseUrl’=>Yii::app()->request->baseUrl).’;’,CClientScript::POS_HEAD);

This will create MyApplication as global variable in javascript which will be accessible all the scripts on current page.

Here we have to carefully choose the names of global js variables (like MyApplication which I have used here) in order not to match with any other variable in javascripts on the page.