admin管理员组文章数量:1516870
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?
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?
Share Improve this question asked Apr 18, 2017 at 12:04 spiffspiff 3281 gold badge3 silver badges18 bronze badges2 Answers
Reset to default 15The good news is that PHP and JavaScript have a similar idea about what values are true and false.
- An empty string will be false on both sides. A string with something in it (except
0in PHP) will be true on both sides. - The number
0will 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.
The value of a form control will always be a string.
If you want a boolean, then you have to encode it somehow and then parse it somehow.
Using a 0 or 1 is a perfectly good approach. You could also use true and false (which you could generate using json_encode on the PHP side) and run the value through JSON.parse. There are numerous other options along similar lines.
本文标签: How to pass boolean values between PHPHTML formsand JavascriptStack Overflow
版权声明:本文标题:How to pass boolean values between PHP, HTML forms, and Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.betaflare.com/web/1738524134a2092327.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。


发表评论