Home » Php » boolean variable values in PHP to javascript implementation

boolean variable values in PHP to javascript implementation

Posted by: admin April 23, 2020 Leave a comment

Questions:

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!

How to&Answers:

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.

Answer:

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+

Answer:

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