I have a PHP program that uses HTML forms and uses JavaScript for validation. There's a hidden field in the HTML form containing a boolean value that gets set by PHP, validated on submission by JavaScript, and passed to another PHP page.
When I tried to use PHP booleans to set the value of the HTML field, JavaScript evaluated it as blank, so I used ones and zeros and compared them numerically instead, and now it works fine.
My question is: what is best practice in this scenario? How do I get JavaScript to read a true/false value in my PHP-driven HTML hidden field without using ones and zeros? Or is that just a bad idea altogether?
Boolean Function If the first parameter is 0, -0, null, false, NaN, undefined, '' (empty string), or no parameter passed then the Boolean() function returns false . The new operator with the Boolean() function returns a Boolean object. Any boolean object, when passed in a conditional statement, will evaluate to true .
This is one of the scalar data types in PHP. A boolean data can be either TRUE or FALSE. These are predefined constants in PHP. The variable becomes a boolean variable when either TRUE or FALSE is assigned.
append accepts only a USVString or a Blob . S you will have to convert your data to string and then parse it later on the backend. You can use JSON. stringify to convert your form object to a string.
In JavaScript, a boolean value is one that can either be TRUE or FALSE. If you need to know “yes” or “no” about something, then you would want to use the boolean function. It sounds extremely simple, but booleans are used all the time in JavaScript programming, and they are extremely useful.
The good news is that PHP and JavaScript have a similar idea about what values are true and false.
0
in PHP) will be true on both sides.0
will be false on both sides. All other numbers will be true on both sides.Since the values of a form will always be strings, as Quentin pointed out in his answer, a good practice might be to use an empty string as false value and something else (e.g. 'true'
) as true value. But I think your way of using 0
and 1
and testing the numerical values is the safest approach because it isn't misleading. (When someone sees 'true'
they might think 'false'
would also be usable for a false value.
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