February
20th, 2008
Have prototype.js automatically eval JSON responses
JSON is the perfect format for passing data from a server to JavaScript. With the prototype.js the JSON string sent by the server is automatically evaluated to a native JavaScript datatype. In order to do this you need to pass the data back with a content-type of application/json.
Step 1
First we’ll need to set up a script (PHP in this case) on the server to return a JSON string and specify the content type. This is easily done using the following code:
$data = array('firstname' => 'Jaisen', 'lastname' => 'Mathai');
header('X-JSON: (' . json_encode($data) . ')');
header('Content-type: application/x-json');
echo json_encode($data);
First we need to write the JSON string to the header as X-JSON. Second we specify the content type as application/x-json. The final step is to echo the JSON string to the screen. If you try to browse to this page you’ll likely be asked to save the page to your computer since the browser might not know what to do with application/x-json data.
Step 2
Next we can set up the JavaScript to make an ajax call and watch it magically convert the text to a native JavaScript object.
new Ajax.Request("/path/to/file/above",
{
onSuccess: function(transport, json)
{
alert("Hello " + json.firstname + " " + json.lastname);
}
}
);
Here we call the php script we created above. Then we specify a callback function that accepts two parameters. The first parameter is the default response object. The optional second parameter holds the evaluated JSON object. Now we no longer need to execute transport.responseText.toJSON(). Simple…but very handy.
