Reputation: 546035
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?Upvotes: 15
Views: 27520
Reputation: 21
I just had this problem that I have solved more simply, maybe for you it 'll be too. In your php file you can do that
if ($_POST[var] == 'null'){ $_POST[var] = NULL; }
Upvotes: 2
Reputation: 30208
This is a weird fix to get Dates
to post correctly in C# MVC
:
$.post(url, JSON.parse(JSON.stringify({ ListOfObjWithDates: listOfObjWithDates })), ...
Upvotes: -1
Reputation: 10721
"null" -> null
could be dangerous if taking in user input.If you didn't want to have convert between JSON, I would use option 3 and simply not send any variables that are null, then use if (!isset($_POST['my-var']))
Upvotes: 0
Reputation: 284796
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
Upvotes: 16
Reputation: 1631
Try converting the javascript object to JSON with:
$.post('test.php', JSON.stringify({ foo : null }));
Upvotes: 1