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); ?>");
1
  • $distance contains an integer value Commented May 3, 2012 at 19:03

3 Answers 3

9

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

var dist = <?php echo $distance; ?>
Sign up to request clarification or add additional context in comments.

2 Comments

yes $distance contains an integer value
Absolutely correct. If $distance is a PHP Integer, there is no need to json_encode, wrap in quotes, or parseInt. Just spit it out.
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; ?>;

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.