Add values to Drupal.settings via drupal_add_js

Public

In your module file:

</> CopyGet raw version
php
  1. drupal_add_js(
  2. array(
  3. 'module_name' => array(
  4. 'apikey' => variable_get('module_name_apikey', ''),
  5. )
  6. ),
  7. 'setting'
  8. );

In your jquery script the variable will be available in Drupal.settings

</> CopyGet raw version
javascript
  1. var apikey = Drupal.settings.module_name.apikey;

Note that to be able to access setting in your javascript it should happen inside Drupal behaviour, like this:

</> CopyGet raw version
javascript
  1. (function ($) {
  2. Drupal.behaviors.example_name = {
  3. attach: function(context) {
  4. var apikey = Drupal.settings.module_name.apikey;
  5. }
  6. }
  7. })(jQuery);

Or inside Jquery's .ready() event:

</> CopyGet raw version
javascript
  1. jQuery(document).ready(function($) {
  2. var apikey = Drupal.settings.module_name.apikey;
  3. });

Comments

malcolm's picture

Hi. In Drupal 7 you can do it this way:

  1. Drupal.behaviors.module_name = {
  2. attach: function(context, settings) {
  3. var apikey = settings.apikey;
  4. }
  5. }

Cool website, greetings ;)
doubouil's picture

drupal_add_js is also implicitely cumulative. If you put the same key for each iteration of a loop, you'll obtain a JS array.

  1. foreach( $nodes as $nid => $node ) {
  2. drupal_add_js(
  3. array( "nodes" => array(
  4. "n" . $nid => $node->title
  5. ), "setting"
  6. );
  7. }

  1. Drupal.settings.nodes = [ { n1 : "Lorem" }, { n2 : "Ipsum" } ];
timonweb's picture

Wow guys, thanks for nice additions!