Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending boolean values with $.ajax to PHP

Tags:

json

jquery

php

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?

like image 685
Mikko Avatar asked Oct 30 '22 16:10

Mikko


1 Answers

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
like image 88
rafwell Avatar answered Nov 09 '22 17:11

rafwell