Cannot pass null to server using jQuery AJAX. Value received at the server is the string "null".

Posted by Tom on Stack Overflow See other posts from Stack Overflow or by Tom
Published on 2010-05-08T13:10:49Z Indexed on 2010/05/08 13:48 UTC
Read the original article Hit count: 224

Filed under:
|
|
|
|

I am converting a javascript/php/ajax application to use jQuery to ensure compatibility with browsers other than Firefox.

I am having trouble passing true, false, and null values using jQuery's ajax function.

Javascript code:

$.ajax
(
   {
      url     : <server_url>,
      dataType: 'json',
      type    : 'POST',
      success : receiveAjaxMessage,
      data:
      {
         valueTrue  : true,
         valueFalse : false,
         valueNull  : null
      }
   }
);

PHP code:

var_dump($_POST);

Server output:

array(3) {
  ["valueTrue"]=>
  string(4) "true"
  ["valueFalse"]=>
  string(5) "false"
  ["valueNull"]=>
  string(4) "null"
}

The problem is that the null, true, and false values are being converted to strings.

The Javascript AJAX code currently in use passes null, true, and false correctly but only works in Firefox.

Does anyone know how to solve this problem using jQuery?


Here is some working code (not using jQuery) to compare with the code not-working code given above.

Javascript Code:

ajaxPort.send
(
   <server_url>,
   {
      valueTrue  : true,
      valueFalse : false,
      valueNull  : null
   }
);

PHP code:

var_dump(json_decode(file_get_contents('php://input'), true));

Server output:

array(3) {
  ["valueTrue"]=>
  bool(true)
  ["valueFalse"]=>
  bool(false)
  ["valueNull"]=>
  NULL
}

Note that the null, true, and false values are correctly received.

Note also that in the second method the $_POST array is not used in the PHP code. I think this is the key to the problem, but I cannot find a way to replicate this behavior using jQuery.

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about AJAX