pass value from PHP to JavaScript

How to pass value from PHP to JavaScript

This post has been viewed 66 times.

In this tutorial we would be learning on how to pass value from PHP to JavaScript.

Are you looking for JavaScript to PHP and not this one? You might want to view How to pass value from JavaScript to PHP instead.

What you’ll need:

  • Basic JavaScript and PHP knowledge.

Step 1: Declare the PHP variable.

In this example we would be using a string variable named $myPHPVar containing the string Hello World!

Step 2: Declare the JavaScript variable.

The JavaScript variable named myJSVar will be the one to receive the data from the PHP variable that we have created in Step 1.

Step 3: Assign the PHP variable to the JS variable.

The PHP variable containing Hello World! is now assigned to our JavaScript variable named myJSVar.

Complete code:

If you might want to check if the variable myJSVar really contains the string Hello World!, you can do it using the JavaScript functions alert() or console.log(). Personally, I would recommend using console.log() and see the output in the console.

Basic usage:

This should print the string Hello World! in the console tab of your debugging tools.

That’s it I hope you have learned something from this tutorial.

Hello, I am a freelance website and mobile application developer. I am also the owner of this website, so if you have any projects for me you can contact me at [email protected] or use the contact page. When I’m not doing some work, I can be found watching Anime/Asian Dramas/American TV Series, playing computer games, and writing tutorials on this website. I run the program repeatedly hoping the error won’t show up next time.