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

Eric.London's picture

Here's a quick debugging technique to capture your output and email it to yourself. This can be useful when you cannot send your debug output to the browser.

<?php
// start output buffer
ob_start();

// display the contents of your variable
print_r($YOURVARIABLE);

// get the contents of the output buffer
$ob = ob_get_contents();

// stop output buffer
ob_end_clean();

// mail contents of output buffer to yourself
mail('YOUREMAIL','Output Buffer Contents',$ob);
?>

Syndicate content