boolean variable values in PHP to javascript implementation [duplicate]

Posted on

boolean variable values in PHP to javascript implementation [duplicate] – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and javascript . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about boolean variable values in PHP to javascript implementation [duplicate].

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!

Solution :

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.

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+

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

Leave a Reply

Your email address will not be published. Required fields are marked *