nickf
nickf

Reputation: 546035

Posting null values via AJAX

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:

  1. Loop through all the variables in JS before you send them and replace with an empty string?
  2. Interpret "null" as null on the server side?
  3. Don't send the variable at all?
  4. Something else?

Upvotes: 15

Views: 27520

Answers (5)

Tktorza
Tktorza

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

Serj Sagan
Serj Sagan

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

helloandre
helloandre

Reputation: 10721

  1. This would not be a good performance idea, especially if large sets of variables are involved.
  2. Possibly. This could be done by looking for all expected values, and ignoring anything else also. directly translating "null" -> null could be dangerous if taking in user input.
  3. This would result in a variable being not set. it would be possible to use !isset() on that variable then. This would be my choice.

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

Matthew Flaschen
Matthew Flaschen

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

Jon Weers
Jon Weers

Reputation: 1631

Try converting the javascript object to JSON with:

$.post('test.php', JSON.stringify({ foo : null }));

Upvotes: 1

Related Questions