This week I haven been playing with the great
EditArea, a webbased sourcecode editor (examples
here). To fetch the data from my PHP server I decided
JSON would be the way to go, due to it's clean nature.
I soon ran into trouble parsing the JSON data my PHP server threw at the client. It took me a while to figure out how to do this nicely with
Prototype, but I found out how at
this page (search for responseJSON, which is the magic keyword...)
On the server side the key is to make PHP send the header "Content-type: application/json", and print the json_decoded data as response. Prototype can fetch this data by doing an Ajax.Request.
On the client side you can let Prototype make an Ajax.Request to the server, and get the property 'responseJSON' from the object you received.
Below is a working example. To get it running you need to create these two files, test.html and test.php . You also need the file
prototype-1.6.0.2.js in the same directory. I suspect it to work on all Prototype versions from 1.6RC upwards.
test.html
<html>
<head>
<title>Prototype/JSON/PHP test</title>
<script language="Javascript" type="text/javascript" src="prototype-1.6.0.2.js"></script>
<script language="Javascript" type="text/javascript">
function LoadFile(id,target){
new Ajax.Request("test.php?action=load&id="+id, {
onSuccess: function(transport) {
var theObject = transport.responseJSON;
$(target).innerHTML = theObject.text;
}, method: "get"
});
}
</script>
</head>
<body>
<a href="javascript:LoadFile(1,'filelist')">File 1</a>
<a href="javascript:LoadFile(2,'filelist')">File 2</a>
<a href="javascript:LoadFile('third','filelist')">File 3</a>
<div id="filelist"></div>
</body>
</html>
test.php
<?php
# Make sure this is the first output.
header('Content-type: application/json');
# The list of files.
$files[1]='This is the first file';
$files[2]='And this the second one!';
$files['third']='This must be the third then...';
# Get ID and create array.
$id=$_GET['id'];
$return['id']=$id;
$return['text']=$files[$id];
# Return the JSON string.
echo json_encode($return);
?>
Code formatted with
Format Code.
Note: Make sure you don't send any other text (that includes spaces or newlines) before sending the header with PHP! This will cause errors that sound like:
"Warning: Cannot modify header information - headers already sent by......"
Good luck! :)