Pass Variable From PHP to JavaScript

Use echo method

In order to pass variable from PHP to JavaScript, you will need to use the echo statement. This will print out the variable for you. For example, if you have a variable named $name, you would use the following code:

This will output a piece of JavaScript code that looks like this:

You can then use the name variable in your JavaScript code.

In case, you are using int parameter, you don’t need quotes.

It will be converted into javascript code as const val=10.

Use json_encode method

Another popular method is to use the json_encode function. This function will take a PHP variable and convert it into a JSON string. For example, if you have a PHP array called $foo, you can convert it to a JSON string like this:

You can then output this JSON string in your HTML code like this:

This will output a piece of JavaScript code that looks like this:

You can then use the foo variable in your JavaScript code.

There are a few other methods that you can use to pass variables from PHP to JavaScript, but these are two of the most popular. Give them a try and see which one works best for you.

Use htmlspecialchars method

We can link the results of a PHP operation by passing the result to the htmlspecialchars() method. This allows us to escape the results because it might not be valid HTML. Another key part of this approach is to create HTML element that’s not visible to the user but is present, and then pass the value to JavaScript within the script tag.

Let’s illustrated this approach by calculating some numbers in PHP and then passing the answer to JavaScript.

When you render the PHP script within a browser, you should see the output below within the console tab.

Was this post helpful?

Leave a Reply

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