Passing JSON via AJAX

AJAX (Asynchronous JavaScript and XML) is quite popular technique in web development. With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Here is a sample code how it works:

Our jQuery (JS):

  // The data to pass
  var json = {
        name: 'Jon Doe',
        age: '33',
        job: null
  // Call AJAX request
    url: 'path/to/handler',
    type: 'POST',
    dataType: 'json',
    data: {
      data: JSON.stringify(json) 
    success: function(data) {
    error: function(xhr, ajaxOption, thrownError) {

The PHP:

// Set the header
header( 'Content-type: application/json; charset=utf-8' );
// Prevent to access the file directly
if( empty( $_POST['data'] ) ) {
  die( 'Do not load this page directly!' );
// Converts the data 
$data = json_decode( stripslashes( $_POST['data'] ), true );
// empty array
$json = array();
// Checks if any data missing
foreach( $data as $key => $value ) {
  $json[$key] = $value ? $value : 'Empty';
// Convert $json array to JSON format and echoes it
echo json_endoce( $json );
// Exit to prevent any issues

Have something on your mind?