jQuery: sending JSON data to PHP with AJAX

Passing JSON data with jQuery and AJAX to Node.js is relatively simple, passing JSON data with jQuery and AJAX to PHP requires a few extra steps.

Instead of trying to send JSON as is, you should only send a well-formed JSON string and let PHP to transform it into an object or an associative array (depending on how you use the json_decode() function).

Bear in mind that PHP not only requires the string to be valid JSON: your string must also be UTF-8 compliant. So with jQuery we can write:


var data = {
  test: $( "#test" ).val()
};
var options = {
  url: "test.php",
  dataType: "text",
  type: "POST",
  data: { test: JSON.stringify( data ) }, // Our valid JSON string
  success: function( data, status, xhr ) {
     //...
  },
  error: function( xhr, status, error ) {
      //...
  }
};
$.ajax( options );

And with PHP we have to take care of the string encoding before using it:


<?php
  header('Content-Type: text/plain');
  $test = utf8_encode($_POST['test']); // Don't forget the encoding
  $data = json_decode($test);
  echo $data->test;
  exit();
 ?>
 
 
Back to top