Menu

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):

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

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
exit;

Have something on your mind?