nickf nickf - 1 month ago 6
Ajax Question

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?


Answer

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
Comments