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?

migrated from stackoverflow.com Feb 20 '12 at 20:13

This question came from our site for professional and enthusiast programmers.

13

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.

2

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.

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

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