pass php variable value to javascript

Im trying to pass the value of a php variable into javascript but i just cant get it to work. Am I doing anything wrong? Below is the line of code I’m working with.

var dist = parseInt("<?php echo json_encode($distance); ?>");

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

$distance is an integer? why don’t you just write

var dist = <?php echo $distance; ?>

Solution 2

If the value in $distance is just an integer, you don’t need the json_encode call. You can just do a php echo of $distance.

Something like

var dist = <?php echo $distance; ?>;

Solution 3

if you right click > view html source in your web browser, you would see for yourself that you have an extra set of quotes.

And, good for you for using json_encode() to output it as a string. That’s an excellent way to safely output a value to javascript. although, if its an integer, theres no need here.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply