Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 200
julio Avatar asked Apr 01 '11 19:04

julio


People also ask

How pass data from PHP to JavaScript function?

We can pass data from PHP to JavaScript in two ways depending on the situation. First, we can pass the data using the simple assignment operator if we want to perform the operation on the same page. Else we can pass data from PHP to JavaScript using Cookies. Cookie work in client-side.

How use JavaScript variable on same page in PHP?

You can easily get the JavaScript variable value on the same page in PHP. Try the following codeL. <script> var res = "success"; </script> <? php echo "<script>document.

How do I pass variables and data from JavaScript to PHP?

The way to pass a JavaScript variable to PHP is through a request. This type of URL is only visible if we use the GET action, the POST action hides the information in the URL. Server Side(PHP): On the server side PHP page, we request for the data submitted by the form and display the result. $result = $_GET [ 'data' ];

Can you echo a boolean in PHP?

To echo a boolean value, we can use the ternary operator ( ? ) in Php.


2 Answers

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.

like image 69
Marc B Avatar answered Sep 28 '22 11:09

Marc B


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+

like image 21
Wh1T3h4Ck5 Avatar answered Sep 28 '22 10:09

Wh1T3h4Ck5