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 found this way to send variables from PHP to Javascript.

Inside the template.tpl.php file, I have the following code.

<?php 
  echo '<div class="drupal-vars" style="display:none;">'.json_encode($variables).'</div>';
?>

Within Javascript, I have the following code:

(function ($) {
  $(document).ready(function() { 
      var variables = jQuery.parseJSON($('.drupal-vars').html()); 
      //Remove if youwant to clean the code.
      $('.drupal-vars').remove();
  });

}(jQuery));

I found another solution, but it's more complicated, although it may be better architectured.

  1. Is there a better way to do it?
  2. How ugly is what I am doing here?
share|improve this question

2 Answers 2

up vote 13 down vote accepted

You'd be better off using drupal_add_js() to pass your object in the JS Drupal.settings object:

// In PHP:
drupal_add_js(array('myModule' => array('variables' => $variables)), 'setting');

// In JS
var variables = Drupal.settings.myModule.variables;

Drupal handles all the conversions of objects/arrays internally and this is just a much cleaner way of doing it...at the moment you're including raw JSON as part of the page output which isn't great in terms of semantics; also bear in mind that search engines will pick up this text even though you're hiding it for users with javascript.

I'd also recommend separating this logic out from the template file itself and put it in a template_preprocess_ function in your theme's template.php file...again it's just cleaner. e.g.

function MYTHEME_preprocess_html(&$vars) {
  $variables = $your_variables;
  drupal_add_js(array('myModule' => array('variables' => $variables)), 'setting');
}

Have a look at the link to the drupal_add_js() function, there are quite a lot of options and you'll probably find them quite useful.

share|improve this answer
    
Thanks againg @Clive. Supereasy. –  Xavi Colomer Feb 3 '12 at 19:04
    
I presume the javascript file also need to be referenced? –  Andrew Welch Mar 15 '13 at 13:51
    
@AndrewWelch Yes, whatever file you're consuming Drupal.settings.myModule from will also need to be included explicitly –  Clive Mar 15 '13 at 14:25

Also, in other cases, you can use drupal_to_js function. It Converts a PHP variable into its Javascript equivalent.

<?php
  $php_settings = array(
    'key1' => 'value1',
    'key2' => 'value2',
  );
?>
<script type="text/javascript">
  var phpSettings = <?php echo drupal_to_js($php_settings); ?>
</script>
share|improve this answer

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.