Take the 2-minute tour ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

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

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

3 Answers

up vote 8 down vote accepted

The standard way to do this in Drupal is with drupal_add_js, using the "setting" type, e.g.:

drupal_add_js(array('variableName' => 'value'), 'setting');

That will make the variable available on the JS side at Drupal.settings.variableName.

share|improve this answer
add comment

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');
share|improve this answer
add comment

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

share|improve this answer
 
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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