Skip to content Skip to sidebar Skip to footer

Boolean Variable Values In Php To Javascript Implementation

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 v

Solution 1:

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

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

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

Solution 2:

This is the simplest solution:

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

$js = "<scripttype=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+

Solution 3:

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

Post a Comment for "Boolean Variable Values In Php To Javascript Implementation"