Error message

The spam filter installed on this site is currently unavailable. Per site policy, we are unable to accept new submissions until that problem is resolved. Please try resubmitting the form in a couple of minutes.

Drupal Add JavaScript Setting Example

Category: 

This describes how to add a custom setting to the JavaScript Drupal.settings variable using PHP

Drupal 7

.module

  drupal_add_js(
    array(
      'lunch_box' => array(
        'soda' => 'sweet and bad',
        'burrito' => 'delicious and sometimes nutricious',
      ),
    ),
    array('type' =>'setting')
  );

.js

(function ($) {

  Drupal.behaviors.my_module = {
    attach: function (context, settings) {
      console.log(Drupal.settings.lunch_box.soda);
      console.log(Drupal.settings.lunch_box.burrito);
    }
  };

}(jQuery));

Drupal 6

drupal_add_js() example:

drupal_add_js(
    array(
      'lunch_box' => array(
        'soda' => 'sweet and bad',
        'burrito' => 'delicious and almost nutricious',
      ),
    ),
    'setting'
  );

Now we can access these variables defined by PHP in JavaScript once the page is ready and loaded:

alert(Drupal.settings.lunch_box.soda);
alert(Drupal.settings.lunch_box.burrito);

You should always place your custom variables in your own "lunch box", that way you don't pollute the Drupal.settings name space:

http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/6

Add new comment