How to make PHP boolean FALSE output only as FALSE

Possible duplicate:
pass variable from php to js

This may seem trivial. I set the value of the PHP variable to false. Then, after some processing, I output some JavaScript variables in a script. This is the code

$a = true; $b = false; echo '<script type="text/javascript"> var a = '.$a.'; var b = '.$b.'; </script>'; 

When the script ends, I get this output:

 var a = 1; var b = ; 

So, I get a syntax error in JavaScript. Now the question is how to have these values ​​as true Boolean values ​​in JavaScript, huh?

Estimated Conclusion:

 var a = true; var b = false; 

I don't need strings like 'true' or 'false' ... or 1 and 0, but only boolean true and false . Any help in this regard, as well as some explanation of why PHP behaves this way?

+6
source share
6 answers
 echo '<script type="text/javascript"> var a = '.($a?"true":"false").'; var b = '.($b?"true":"false").'; </script>'; 

I suppose you can't just echo true / false to get a word, you need to convert it to a string.

+9
source

Use json_encode .

 $a = true; $b = false; echo '<script type="text/javascript"> var a = '.json_encode($a).'; var b = '.json_encode($b).'; </script>'; 
+4
source

Another way to do this is to use var_export()

 echo '<script type="text/javascript"> var a = ', var_export($a), '; var b = ', var_export($b), '; </script>'; 
+3
source

Encode as JSON.

 $ php <?php echo json_encode(true) . "\n"; echo json_encode(false) . "\n"; true false 
+2
source

I suspect this will work and will be easy to add:

 ($val ? "true" : "false") 
+1
source

I would use json_encode () on the php side and JSON2 on the js side to pass variables. (json2 is included in most js frameworks)

 <?php $js_vars = json_encode(array( 'a' => true, 'b' => false, )); ?> <script> JS_VARS = JSON.parse('<?php print $js_vars?>'); console.log(JS_VARS.a, JS_VARS.b); </script> 

It works for single variables, but I would recommend grouping the variables so that they do not pollute the global javascript object.

+1
source

Source: https://habr.com/ru/post/921267/


All Articles