330 Locust Dr.
Verona, WI 53593
Powderkeg Web Design
Message Us

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

April 11, 2017

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:

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:


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

Lead Developer

Nick is an ambitious and versatile developer with a wide range of talents. He is an efficient coder that utilizes his resources in order to achieve both his and the clients’ goals. His Alma Mater is the University of Wisconsin – Stevens Point where he graduated with honors in Web and Digital Media Development.