Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 647
spiff Avatar asked Apr 18 '17 12:04

spiff


People also ask

How do you pass a boolean value in JavaScript?

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 .

Is boolean supported in PHP?

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.

How do you append boolean to form data?

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.

Can we use boolean in JavaScript?

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.


1 Answers

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.

like image 75
A Person Avatar answered Sep 25 '22 23:09

A Person