For example we want to add an api key as a variable to our jquery script. In drupal we define our apikey using a settings form. We add the js using drupal_add_js. Notice that the second parameter says 'setting', this is used to tell the drupal javascript system to add the array as a setting in scripts. The Jquery object is allready extended with Drupal.settings and this is where our setting will be available.
To avoid namespace clashes it is good practice to put variables in arrays by module.
<?php
function module_name_settings() {
$form['module_name_apikey'] = array(
'#type' => 'textfield',
'#title' => t('Google api key'),
'#default_value' => variable_get('module_name_apikey', ''),
'#size' => 60,
'#weight' => -5,
'#description' => l(t('Get your google api key here'), '<a href="http://code.google.com/apis/maps/signup.html'">http://code.google.com/apis/maps/signup.html'</a>),
);
system_settings_form($form);
}
//Implementation of hook init()
function module_name_init() {
drupal_add_js(
array(
'module_name' => array(
'apikey' => variable_get('module_name_apikey', ''),
)
),
'setting'
);
}
?>
In your jquery script the variable will be available in Drupal.settings
var apikey = Drupal.settings.module_name.apikey; //To view output in firebug console.log(apikey); //If you dont use firebug alert(apikey);
Links
[1] https://dominiquedecooman.com/blog-topics/jquery-0