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); ?>");
share|improve this question
$distance contains an integer value – cclerville May 3 '12 at 19:03

3 Answers

up vote 9 down vote accepted

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

var dist = <?php echo $distance; ?>
share|improve this answer
yes $distance contains an integer value – cclerville May 3 '12 at 19:02
Absolutely correct. If $distance is a PHP Integer, there is no need to json_encode, wrap in quotes, or parseInt. Just spit it out. – JAAulde May 3 '12 at 19:03

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; ?>;
share|improve this answer

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.

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.