I have set theme handler for a form in Drupal and this handler has a template file. What is the easiest way to send a value from PHP to JavaScript in that include file?
4 Answers
The standard way to do this in Drupal is with drupal_add_js, using the "setting" type:
drupal_add_js(array('variableName' => 'value'), 'setting');
That will make the variable available on the JS side at Drupal.settings.variableName.
Few more examples on drupal_add_js,
It's better to specify your module name while adding JS variable to avoid any issues,
drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');
In case you want to execute some JS code after the DOM is initialized,
drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
Also, the #attached
key to a form can be used for sending php variable to js.
$my_variable = 'My custom value';
$form['some-element']['#attached']['js'] = array(
array(
'data' => drupal_get_path('module', 'my_module') . '/js/script.js',
),
array(
'data' => array(
'variable' => $my_variable,
),
'type' => 'setting',
),
);
This can be used in hook_form_alter
for example.
Easiest way is just to echo it out into a script tag:
<script type="text/javascript">
var variableName = <?php echo $variable ?>;
</script>
If Drupal uses a templating language, you need to replace the <?php echo... ?>
with the relevent output method...
-
also if variable is a string you should put it in a quotes and escape if needed.– kodishaCommented Mar 30, 2010 at 15:49
-
1Scott's suggesting, using Drupal.settings, is definitely the correct way to go for this.– ChaulkyCommented Feb 20, 2012 at 21:04
-
1