background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount
Eric.London's picture

In this tutorial, I'll show a way to pass PHP/Drupal variables to javascript/jquery using drupal_add_js(), and a way you can debug javascript variables using the FireBug console.

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);
 
});

When viewing this page in a browser, you'll see the following. The javascript popup window is using variables passed directly from a Drupal/PHP array:
javascript popup

The console.debug() javascript method was used to send data directly to the FireBug console. If you open FireBug, you'll see the following:
FireBug Console

If you click on the Object shown, you can drill into the variables further:
FireBug Console

Today I wanted to add a unique identifier to each menu item in the primary links so I could theme each one individually. In this example, I added a incrementing class to each menu item so I could add an image via css. Here's a snippet of my theme function (found in template.php):

<?php
function MYTHEME_preprocess_page(&$variables) {
 
$linkCount = 0;
  foreach (
$variables['primary_links'] as $k => $v) {
   
$linkCount++;
   
$class = trim($v['attributes']['class'] . " nav$linkCount");
   
$variables['primary_links'][$k]['attributes']['class'] .= $class;
  }
}
?>

Eric.London's picture

The Drupal framework and theme engine are very powerful. Whenever I override a function, I start with the following code to see what variables are defined in the current function scope...

<?php
echo "<pre>";
print_r(get_defined_vars());
echo
"</pre>";
?>

Syndicate content