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"}
</script>

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

php_variables.sheetID

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

0 thoughts on “Passing PHP variables to JavaScript

  • 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!

    • Scott Tirrell says:

      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:

       'test'
      );
      
      ?>
      
      
      	JavaScript test
      
      
      
      
      <script type="text/javascript">
      	alert(php_variables.sheetID);
      </script>
      
      
      

      Let me know if this helps!

      Scott

    • 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 *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>