7

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 4

14

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.

1

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');
1

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.

-10

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...

3
  • also if variable is a string you should put it in a quotes and escape if needed.
    – kodisha
    Commented Mar 30, 2010 at 15:49
  • 1
    Scott's suggesting, using Drupal.settings, is definitely the correct way to go for this.
    – Chaulky
    Commented Feb 20, 2012 at 21:04
  • 1
    This is not a drupal standard. Commented Nov 19, 2013 at 5:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.