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!
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.
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.
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' ];
To echo a boolean value, we can use the ternary operator ( ? ) in Php.
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+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With