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.

3 thoughts on “Passing PHP variables to JavaScript”

  1. Hi, I have tried your approach but it does not work for me, can you explain further how to read the value of php_variables.sheetID in Javascript local variable?

    Thanks in advance!

    1. Hello Sam,

      Sorry for the delay in getting back to you. Do you happen to have an example of the code that you are trying to use? Here is a really simple PHP script to show how to set and retrieve the JavaScript variable:

      < ?php
      $javascriptVariables = array(
      	'sheetID' => 'test'
      ?>< !doctype html>
      	JavaScript test
      < ?php
      if (!empty($javascriptVariables)) {
      	echo "<script type='text/javascript'>";
      	echo "var php_variables = " . json_encode($javascriptVariables) . "\n";
      	echo "</script>";
      <script type="text/javascript">

      Let me know if this helps!


    2. It all should work totally fine.
      For me it didn’t work at first, because inside the js script I used “php_variables” in $(document).ready()…function.
      So I put php_variables outside and it worked.

      Thanks Scott!

Leave a Reply

Your email address will not be published. Required fields are marked *