How to pass boolean values between PHP, HTML Forms and Javascript
I have a PHP program that uses HTML forms and uses JavaScript for validation. There's a hidden field in an HTML form containing a boolean value that is set by PHP, checked when JavaScript is submitted, and passed to another PHP page.
When I tried to use PHP booleans to set the value of an HTML field, JavaScript evaluated it as empty, so I used those and zeros and compared them numerically instead, and now it works fine.
My question is, what is the best practice in this scenario? How do I get JavaScript to read the true / false value in my PHP hidden HTML field without using those and zeros? Or is it just a bad idea?
source to share
The good news is that PHP and JavaScript have a similar idea of which values are true and false.
- An empty string will be false on both sides. A string with something in it (except
0
in PHP) will be true on both sides. - The number
0
will be false on both sides. All other numbers will be true on both sides.
Since form values will always be strings, as Quentin pointed out in his answer, it might be good practice to use an empty string as a false value and something else (for example 'true'
) as a true value. But I think your way of using 0
and 1
and testing numeric values is the safest approach because it is not misleading. (When someone sees it 'true'
, they might think that would 'false'
also be used for a false value.
source to share
The value of the form control will always be a string.
If you want boolean then you need to code it somehow and then parse it somehow.
Using 0 or 1 is a great approach. You can also use true
and false
(which you could generate with json_encode
PHP side) and run the value through JSON.parse
. There are many other options in similar directions.
source to share