Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
181
rated 0 times [  184] [ 3]  / answers: 1 / hits: 25402  / 13 Years ago, fri, april 1, 2011, 12:00:00

I've run into an odd issue in a PHP script that I'm writing-- I'm sure there's an easy answer but I'm not seeing it.



I'm pulling some vars from a DB using PHP, then passing those values into a Javascript that is getting built dynamically in PHP. Something like this:



$myvar = (bool) $db_return->myvar;

$js = <script type=text/javascript>
var myvar = . $myvar . ;
var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
</script>;


The problem is that if the boolean value in the DB for myvar is false, then the instance of myvar in the $js is null, not false, and this is breaking the script.



Is there a way to properly pass the value false into the myvar variable?



Thanks!


More From » php

 Answers
23

use json_encode(). It'll convert from native PHP types to native Javascript types:



var myvar = <?php echo json_encode($my_var); ?>;


and will also take care of any escaping necessary to turn that into valid javascript.


[#92960] Thursday, March 31, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josefn

Total Points: 251
Total Questions: 93
Total Answers: 84

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;