Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

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!

share|improve this question
add comment

marked as duplicate by Benjamin Gruenbaum yesterday

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3 Answers

up vote 17 down vote accepted

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.

share|improve this answer
1  
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 1 '11 at 19:20
    
awesome trick :D thanks –  Ashish Panwar Jan 22 '13 at 18:09
    
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
add comment

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+

share|improve this answer
add comment
$js = "<script type=text/javascript>
    var myvar = " . ($myvar ? 'true' : 'false') . ";
    var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
   </script>";
share|improve this answer
    
var_export($myvar)? All you guys forgot var_export()... :) –  Wh1T3h4Ck5 Apr 1 '11 at 19:22
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.