Pass PHP Varibale to Javascript – The Easy Way

Young Blanding's Turtle stretches out it's neck.

Taking a variable from PHP and sending it to javascript seems like a really simple thing to do. But it’s not. I’m sure if you ended up here, you’ve tried and tried to get it to work with little success. I’m not sure what the people online are talking about, none of those solutions seem to be functional in most situations.

But there IS an easy way. It’s just as simple as I’m sure you’ve imagined it would be. Essentially, all you are going to be doing is defining your PHP variable and then defining your javascript variable with a PHP echo. The trick? Do it in your site’s section. Let’s take a look at an example.

That’s all it takes! Remember, it’s key to include this in the HEAD section of our site, otherwise it won’t work. But the beauty here is that you can now use our_js_variable in javascript anywhere we want, and it will have the value “mittens”. Nothing more to it!

About Brian Johnson

Brian Johnson is a website developer and designer living in Minneapolis, Minnesota with a passion for code and WordPress. He spends his days building WordPress websites for small businesses, developing new code with the online community, and living life.

Leave a Reply

Your email address will not be published. Required fields are marked *