Is it possible to send JSON data from the client side using ajax (with jQuery), to a PHP page and use json_decode with all the variables exactly the same data type? I thought JSON was suppose to preserve this but it seems it doesn't work if you send it to PHP. If it doesn't do this then I'm not sure why I should ever be using JSON. I might as well just use a standard POST request.
My problem is that I need to send data to PHP for it to be inserted into MySQL which requires the right variable types being inserted, but when the data arrives from JSON it is all converted to a string. I think I'm misunderstanding what JSON is suppose to be used for. Most likely, and if so can anyone explain this to me?
Does this mean I need to manually convert everything on the PHP side all the time throughout my entire web application? That would be a real pain.
// JavaScript:
$.ajax({
type: "POST",
url: "program.php",
data: {
posting: true,
json: JSON.stringify({
posting: true,
id: 6, // should remain an integer
})
},
success: function(data) {
console.log(data);
}
});
// PHP:
if (array_key_exists("posting", $_POST)) {
$result = json_decode($_POST["json"]);
echo gettype($result->id); // string (all values in $result are strings still)
exit();
}
EDIT: The reason I'm worried about variable types is because I am trying to use prepared statements with MySQL and the bind_param function requires you to enter the variable types. This is a PHP function I created to handle this for me:
public static function insert($query, $params) {
$statement = mysqli_prepare(self::$connection, $query);
foreach ($params as $value) {
switch (gettype($value)) {
case "boolean":
$value = (int) $value;
case "integer":
$statement->bind_param("i", $value);
break;
case "double":
$statement->bind_param("d", $value);
break;
case "string":
// it is ALWAYS a string even though some as suppose to be integers
$statement->bind_param("s", $value);
break;
default:
echo "error type: " . gettype($value);
return;
}
}
$statement->execute();
$statement->fetch();
$result = $statement->get_result();
$statement->close();
return $result;
}