39

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!

julio
  • 6,360
  • 15
  • 57
  • 81
  • 2
    IMO this question is NOT a duplicate of the question it is linked to. This question is way more specific. Thankfully it had already been answered usefully, before being locked. – Katinka Hesselink Jun 11 '19 at 15:04

3 Answers3

80

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.

Marc B
  • 348,685
  • 41
  • 398
  • 480
  • 2
    very clever solution Marc, and it works well! Thanks. I should also point out that the issue turns out to have been in casting it to a boolean-- if I cast to int instead, it brings back a 0/1 value and this can be passed to the JS as an int, and evaluated as true/false by JS normally. – julio Apr 01 '11 at 19:20
  • Works! Would be nice to know if this could be done without `json` trick. – dev.e.loper Sep 20 '13 at 18:55
  • it could, but then you're responsible for producing valid javascript code. remember that json **IS** javascript... so build your own system when you can just use the perfectly good pre-built on? – Marc B Sep 20 '13 at 18:59
  • THIS IS CORRECT. Since "JSON" means "JavaScript Object Notation" I would stick with this method over var_export which is based on a different notation specific to PHP and not JavaScript. – tfont Nov 30 '18 at 09:50
5

This is the simplest solution:

Just use var_export($myvar) instead of $myvar in $js;

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

Note: var_export() is compatible with PHP 4.2.0+

Wh1T3h4Ck5
  • 8,295
  • 9
  • 56
  • 77
3
$js = "<script type=text/javascript>
    var myvar = " . ($myvar ? 'true' : 'false') . ";
    var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
   </script>";
Hamish
  • 22,072
  • 7
  • 50
  • 67