nickf nickf - 1 year ago 81
Ajax Question

Posting null values via AJAX

Using the jQuery

function, if you send a
value, it arrives at the server side as
. Example:


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


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
    on the server side?

  3. Don't send the variable at all?

  4. Something else?

Answer Source

I would encode it into JSON.


  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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download