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:
1 2 3 4 |
<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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<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.