Press "Enter" to skip to content

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:

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.