Passing PHP variables to JavaScript

I was recently working on a project in CodeIgniter and I was setting numeric variables with constants for things like locations (1 = Maine, 2 = New Hampshire, etc.). This all worked fine but when it came to doing some JavaScript AJAX work I didn’t have access to these constants. One of the advantages to using these constants is that I did not want to have to change the value in more than one place if a value changed or I wanted to add a new location, for example. My way to solve this was to pass my PHP variables through to JavaScript using json_encode.

In my CodeIgniter controller, I set the variables I wanted to use in JavaScript:

$footerData['javascriptVariables'] = array(
  'sheetID' => $sheetID

Then, in the footer, I checked for the existence of $javascriptVariables and, if it is not empty, I echoed out the json_encoded value:

// Were there any variables set via PHP for use in the JavaScript?
if (!empty($javascriptVariables)) {
  echo '<script type="text/javascript">';
  echo "var php_variables = " . json_encode($javascriptVariables) . "\n";
  echo '</script>';

This results in something like:

<script type='text/javascript'>
var php_variables = {"sheetID":"8"}

Then, in my JavaScript, I can easily get access to the sheetID set in PHP:


I suspect that I could also automate the process of making all my PHP constants available in JavaScript by usingĀ get_defined_constants.

Debugging Google Analytics

I was recently working with Google Analytics and discovered the Google Analytics Tracking Code Debugger. In the past, one of the biggest frustrations I had was that I would make a change and then have to wait until the next day to see if the changes worked. I guess that the time to see results with Google Analytics has been lessened recently but, in my experience, it still isn’t instantaneous. Google Analytics Debugger gives you instant feedback during development:

This allows you to see the results in a tool like Firefox’s Firebug while testing on a local development server. It is much nicer than running tests and coming back hours later only to find that there was an error in your code. I am not sure when this tool was made available, but I wish I knew about it earlier.