Skip Navigation
Madison, Wisconsin
Powderkeg Web Design
April 11, 2017

Web Dev Tid Bit (WDTB): Easy ways to pass PHP info to Javascript

Nick
Nick
Web Dev Tid Bit (WDTB): Easy ways to pass PHP info to Javascript

Every now and then you’ll want some information to be available to javascript that is decided real time server side. If it is a small project you are working on there are 2 quick ways to achieve this:

1. echo PHP variable values directly in to Javascript

You can insert <?php ?> tags directly in to your javascript <script></script> tags:

<script>
   var multiplier = <?php echo 6; ?>;
   alert(5*multiplier);
</script>

This should work like a charm, but it isn’t the cleanest way to do things. You end up with a jumble of php and javascript code intertwined. It makes it really hard to debug or untangle the languages sometimes.

 

2. echo PHP variable to an html element as a data attribute

A better way is to use data attributes on specific HTML elements. This keeps the PHP separate from the Javascript:

<div id="item" data-category="<?php echo 'testing'; ?>">
   This is an item
</div>

<script>
   //Vanilla
   alert(document.getElementById('item').dataset.category);

   //OR with jQuery
   $(function() {
      alert($('#item).data('category'));
   });

</script>

 

For a more in depth look with pros and cons, you can check out this great stackoverflow question and answer.

Nick Kalscheur

Nick Kalscheur

Lead Developer