7

This question already has an answer here:

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?

The tutorial goes like:

I'll start by creating a hook_menu() implementation to establish a page callback:

<?php
function helper_menu() {

  $items = array();

  $items['js-vars'] = array(
    'title' => t('Javascript Variables'),
    'description' => t('Javascript Variables'),
    'page callback' => 'helper_page_callback_js_vars',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,    
  );

  return $items;

}
?>

Next, I'll define the page callback:

<?php
function helper_page_callback_js_vars() {

  // include module javascript file
  drupal_add_js(drupal_get_path('module','helper') . '/js/helper.js');

  // define variables you'd like to pass to the DOM
  $js_vars = array(
    'js_vars' => array(
      'message' => t('Hello @username', array('@username' => $GLOBALS['user']->name)),
      'an_array' => array(
        'color' => t('red'),
        'name' => t('Eric'),
      ),
    ),
  );

  // pass variables to javascript
  drupal_add_js($js_vars, 'setting');

  // generate some page output
  return "TEST";

}
?>

And here is the contents of the javascript include file I stuck in my module directory:

$(document).ready(function(){

  // debug variables directly in FireBug
  console.debug(Drupal.settings.js_vars);

  // popup mesage passed from Drupal
  alert(Drupal.settings.js_vars.message);

});

marked as duplicate by kiamlaluno Aug 21 '17 at 18:27

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

16

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.

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

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

an example on how to convert node datas to a js object:

in template.php

function mythemename_preprocess_node(&$variables){  
     drupal_add_js(array('node' => $variables['node']), 'setting');
}

in the page.tpl.php

  var node = Drupal.settings.node; 
 // console.log(node);

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