Thursday, 18 April 2019

php - Cannot obtain correct Boolean value when sent in ajax




let's say we have the following ajax:



$.ajax({

url:'myURL.php',
data:{
ac:'do',
isDoable:false
}
});


Now at the back end when reading the call data, the isDoable is a string, and trying to cast it as Boolean:




$isDoable = (bool) $_REQUEST['isDoable'];


results in $isDoable always being true, even when sent as false.
When I encountered this issue I gave up and simply treated it as a string if($_REQUEST['isDoable'] == 'true')



But I cannot get over it! why is this unexpected behavior, and is there a way around it?


Answer



As you are not sending a JSON data via POST (that could be handle correctly with the json_decode) your string "true" or "false" will always be the boolean true, because PHP will assume that, as a non empty string, your var should be converted to the true boolean value.




So, you should use string comparison instead in your case.



In example:



$value = (bool)"test"; // whatever value, not empty string
var_dump($value);


is the boolean true




$value = (bool)"";
var_dump($value);


is the boolean false


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...