Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  33] [ 7]  / answers: 1 / hits: 20643  / 7 Years ago, tue, april 18, 2017, 12:00:00

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?


More From » php

 Answers
19

The 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 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 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.


[#58111] Saturday, April 15, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jenamackennac

Total Points: 304
Total Questions: 110
Total Answers: 107

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
jenamackennac questions
Fri, Feb 18, 22, 00:00, 2 Years ago
Wed, Apr 21, 21, 00:00, 3 Years ago
Thu, Apr 1, 21, 00:00, 3 Years ago
Tue, Feb 2, 21, 00:00, 3 Years ago
;