OTARIKI OTARIKI - 1 year ago 58
jQuery Question

send post data from js to php using ajax without type cast

I have object in javascript and I need send this object to php using ajax.

I can "just send" this object, but my problem is that I need send object value types exactly as they are and not everything as string: meaning NULL as NULL, boolean values as boolean and so on...

Trying this:

var js_object= <?php echo json_encode( array("a"=>NULL, "b"=>TRUE, "C"=>1.1) ); ?>;

type: "POST",
url: "some.php",
dataType: "json",
data: JSON.stringify(js_object),
contentType: "application/json; charset=UTF-8",
success: function(msg){

but this does not sends data to server at all. and not gives any error also. where I am wrong ?

Answer Source

There is nothing wrong with your code.
I've just add a snippet with post query to httpbin.org:

  type: 'POST', 
  url: '//httpbin.org/post', 
  data: JSON.stringify({name: 'test', 'null': null, 'true': true}), 
  success: onSuccess, 
  error: onError,
  dataType: 'json', 
  contentType: 'application/json; charset=UTF-8'
function onSuccess(data){
  // data is parsed json response
  console.log('Request copy:', data.json);
  console.log('Full response', data);
function onError(xhr) {
  console.log(xhr.status, xhr.responseText);
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>

Server side sample script:

  $json = file_get_contents('php://input');
  $data = json_decode($json, true);
  header('Content-type: application/json');
  echo json_encode($data);