Passing configuration from PHP to JavaScript

You can store application parameters in your configuration file protected/config/main.php that we can access using Yii::app()->params['paramName']. When your application uses the JavaScript code, it is handy to have these parameters available for it. Let's see how to do it in a simple and effective way.

Getting ready

  1. Set up a fresh application using the yiic webapp tool. It should generate an application parameters array in protected/config/main.php:
    'params'=>array(
       // this is used in contact page
       'adminEmail'=>'[email protected]',
    ),
  2. Add additional parameters as follows:
    'params'=>array(
       // this is used in contact page
       'adminEmail'=>'[email protected]',
       'alert' => array(
          'enabled' => true,
          'message' => 'Hello there!',
       ),
    ),

How to do it...

  1. Create a controller named protected/controllers/AlertController.php as follows:
    <?php
    class AlertController extends Controller
    {
      function actionIndex()
      {
        $config = CJavaScript::encode(Yii::app()->params->toArray());
        Yii::app()->clientScript->registerScript('appConfig', "var config = ".$config.";", CClientScript::POS_HEAD);
    
          $this->render('index'),
       }
    }
  2. Moreover, create a view named protected/views/alert/index.php as follows:
    <script>
       if(config && config.alert && config.alert.enabled && config.alert.message){
            alert(config.alert.message);
       }
    </script>
  3. Now, if you run the alert controller of the index action, you should get a standard JavaScript alert window saying Hello there!, as shown in the following screenshot:
    How to do it...

How it works...

We use CJavaScript::encode , which converts PHP data structures into JavaScript ones to turn Yii application parameters into a JavaScript array. Then, we register a script that assigns it to a global variable config. Then, in our view's JavaScript code, we just use this global variable config.

See also

  • The Managing assets recipe
  • The Loading a block through AJAX recipe
  • The Rendering content at the client side recipe
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.109.30