Back to the index of articles and examples

Sending raw JSON over POST

If everything goes fine, a transaction should have been initiated against this very same PHP script and one of the elements of a JSON array should be returned and shown in an alert.

The alert should read "there should be children here".

You might get an alert telling you that function json_decode does not exist. Run a phpinfo() on your server, your PHP interpreter might not have the JSON option compiled in.

My ISP does not have JSON compiled in its interpreter. The running code in my server actually uses Services_JSON, an external package coded in PHP so that it can run in any version of PHP.

Another gotcha is that you might not have the corresponding wrappers enabled so that you cannot open php://input. The PHP Manual lists several ways to read the raw POST input.

The code

	if ($_GET['data']) {
		$handle = fopen('php://input','r');
		$jsonInput = fgets($handle);
		$decoded = json_decode($jsonInput,true);
		echo $decoded[2]['title'];
		/* If you don't have native JSON support in PHP,
		   comment the two lines above and uncomment the lines below.
		   Adjust the path to the library as needed.
		require '/scripts/Services_JSON.php';
		$json = new Services_JSON();
		$decoded = $json->decode($jsonInput);
		echo $decoded[2]->title;
	} else {
		<title>JSON over post</title> 
		<script type="text/javascript" src="" ></script>
		<script type="text/javascript" src="" ></script>
		<script type="text/javascript" src="" ></script>
		<dd>see self-referencing.</dd>
		YAHOO.util.Connect.initHeader("Content-Type","application/json; charset=utf-8");
				success:function(o) {
				failure: function (o) {
				'Label 0',
				{type:'Text',label:'text label 1',title:'this is the tooltip for text label 1', editable:true},
				{type:'Text',label:'branch 1',title:'there should be children here', expanded:true, children:[
					'Label 1-0'
				{type:'Text',label:'text label 2',title:'this should be an href', href:'', target:'something'},
				{type:'HTML',html:'<a href="">YUI</a>',hasIcon:false},
				{type:'MenuNode',label:'branch 3',title:'this is a menu node', expanded:false, children:[
					'Label 3-0',
					'Label 3-1'

<?php } ?>