Using the jQuery $.post
function, if you send a null
value, it arrives at the server side as "null"
. Example:
Javascript:
$.post('test.php', { foo : null });
PHP:
var_dump($_POST['foo']); // string(4) "null"
I understand why this is so, but was wondering the best way to work around the limitation? Should you:
"null"
as null
on the server side?I would encode it into JSON.
E.g.:
$.ajax({
url: 'test.php',
type: 'POST',
data: JSON.stringify({foo : null}),
contentType: "application/json",
success: function(data) {
// ...
}
});
You can use json_decode
on the server, and the types will be preserved:
$msg = json_decode(file_get_contents("php://input"));
var_export($msg->foo); // NULL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With