5

I post data to a PHP backend using jQuery $.ajax:

$.ajax({
    url: "server.php",
    method: "post",
    data: {
        testVariable: true
    }
});

On the server side I tried die(gettype($_POST["testVariable"])); which returns string.

I'm trying to save the JSON data posted from Javascript to a MySQL database, but boolean values get quoted which is not what should happen.

What gets inserted is {"testVariable": "true"} and what I need is {"testVariable": true}. How do I accomplish this?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Mikko
  • 607
  • 2
  • 9
  • 22
  • 5
    This is normal behaviour, you can really only send strings, not booleans, so booleans are converted to strings when posted – adeneo Nov 16 '16 at 13:56
  • 1
    on the php side, you can use json_decode http://php.net/manual/en/function.json-decode.php to parse the incoming data into an array or object. – Loopo Nov 16 '16 at 14:01
  • 1
    or just send 1 as true and 0 as false in jor ajax, and convert it in your php to boolean. (boolean true is original an 1 and false a 0 (binary)) – Timon Post Nov 16 '16 at 14:22
  • Yes send 1 or 0 – Jereme Nov 16 '16 at 14:31
  • 1
    Possible duplicate of [Bool parameter from jQuery Ajax received as literal string "false"/"true" in PHP](http://stackoverflow.com/questions/7408976/bool-parameter-from-jquery-ajax-received-as-literal-string-false-true-in-php) – san san Nov 16 '16 at 14:35

1 Answers1

2

This is the expected behavior. On PHP you need convert the string to boolean, if you need, using a ternary or the method you like. Or you can send 1/0 to represent boolean state.

Converting like that:

$testVariable = ($_POST['testVariable'] === 'true'); //return the boolean evaluation of expression
rafwell
  • 429
  • 1
  • 4
  • 12