views:

49

answers:

3

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?
+3  A: 

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
Matthew Flaschen
For those browsers that don't have a native JSON object you can use [http://www.json.org/json2.js]
meouw
A: 

Try converting the javascript object to JSON with:

$.post('test.php', JSON.stringify({ foo : null }));
Jon Weers
A: 
  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']))

contagious