Drupal 6: Passing PHP variables to Javascript/jQuery and debugging with FireBug

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

Updated: