0

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?

Sebas
  • 21,192
  • 9
  • 55
  • 109
Khalid Dabjan
  • 2,697
  • 2
  • 24
  • 35
  • 7
    How to convert string to boolean in php: http://stackoverflow.com/questions/7336861/how-to-convert-string-to-boolean-php –  Aug 20 '13 at 19:01
  • do a `var_dump($_REQUEST)`, and you'll see EXACTLY what's coming in. if JS is encoding that true as the literal string `'false'`, then a non-empty string will always evaluate as boolean `true` in php. – Marc B Aug 20 '13 at 19:01
  • 1
    A query string is always a string and always has the format of `http://somedomain.com/ourpage?key=value`. No mater you use JavaScript boolean. Technically its just a string as long as its a query string request. You are using $ajax with Get method.Hence its obviously treated as string. What you do is exactly the right method. – Clain Dsilva Aug 20 '13 at 19:10
  • See this post: http://stackoverflow.com/questions/3654454/boolean-variables-posted-through-ajax-being-treated-as-strings-in-server-side – mmcachran Aug 20 '13 at 19:26

1 Answers1

0

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

MatRt
  • 3,494
  • 1
  • 19
  • 14