Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 540
nickf Avatar asked Jun 15 '10 04:06

nickf


1 Answers

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
like image 132
Matthew Flaschen Avatar answered Oct 23 '22 13:10

Matthew Flaschen