43

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!

1
  • 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. Commented Jun 11, 2019 at 15:04

3 Answers 3

90

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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.
Works! Would be nice to know if this could be done without json trick.
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?
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.
I would suggest: var myvar = <?php echo json_encode($my_var, JSON_PRETTY_PRINT); ?>; because JSON_PRETTY_PRINT will make it a safe JavaScript value.
7

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+

Comments

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

1 Comment

var_export($myvar)? All you guys forgot var_export()... :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.