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?


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(
     'data' => drupal_get_path('module', 'my_module') . '/js/script.js',
      '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 ?>;

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. – kodisha Mar 30 '10 at 15:49
  • 1
    Scott's suggesting, using Drupal.settings, is definitely the correct way to go for this. – Chaulky Feb 20 '12 at 21:04
  • 1
    This is not a drupal standard. – Jayendra Kainthola Nov 19 '13 at 5:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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