2

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); ?>");
cclerv
  • 2,921
  • 8
  • 35
  • 43

3 Answers3

9

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

var dist = <?php echo $distance; ?>
Sebastian Breit
  • 6,137
  • 1
  • 35
  • 53
1

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; ?>;
Lucas Holt
  • 3,826
  • 1
  • 32
  • 41
1

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.

goat
  • 31,486
  • 7
  • 73
  • 96