IMG-LOGO
Home Tutorial Pass -> PHP Variable to JavaScript

Pass -> PHP Variable to JavaScript

by MH RISHAD - 15 Oct 2018
IMG

For something seemingly so straight-forward, you would think that the information out there would be a bit better on this subject. Passing a variable from PHP to JavaScript is actually very easy! There are just a couple things you need to keep in mind and some ways to do it to ensure it actually works.

I find that putting the following code into the 

 section of my website is the most foolproof method:

 

1

2

3

4

$php_variable = 'string'; //Define our PHP variable. You can of course get the value of this variable however you need.

?>

        

That’s it! You just define the PHP variable first, then echo it into a basic JS variable declaration statement. I know there are lots of ways to define a JavaScript variable, but this is the one I find works in the most circumstances. I’m not an expert here, but most of the others seem to not work a lot of the time.

A few things to keep in mind for this:

1. The PHP variable needs to be defined before the JS one.
2. The JS variable needs to be defined before you actually use it anywhere. This seems obvious, but if you forget this fact and try to put this declaration into the footer of your site and then use it in the content, you’ll find it doesn’t work! That’s why I like to put this in the head section of my website. Or, if you were in WordPress or another CMS, make sure to place it in the header.php file of your active theme.

Additionally, you should be aware that if your variable is not a string and is instead a number, you would want to define it without the quotes around it, i.e.:

 

1

 

Hard to go wrong with any of this. There are of course more complicated ways to use this, but I’m not going to go into any of those here. Let me know if you have any problems!

Share:

Leave a Comment

Required fields are marked *