Confessions of a Guru....

30 September 2007

Earthquake

Hmm, an earthquake ... 10:49 NZDT felt in Dunedin, went on for about a minute. Slight rolling/shaking, kind of cool :)

Custom Search

28 September 2007

Prototype and AJAX

Lately I've been tinkering with the Ajax features of the Prototype library. I was pleasantly surprised when I saw how easy it was to make an Ajax call and do something as a result, and also how Prototype has an auto-evaluation feature if you return your JSON encoded response in the X-JSON header of the response (although after reading through this I think I'll avoid using it for anything serious).

For example let's that you want to populate the contents of a select element with some options from an Ajax call. We'll ask our server (which we'll write in a second too) to give us a brief list of musical genres.

First of all we need to do something with the response and for this example we'll add the genres to a select element:
<select id="genre" />
That's all that we need for this as we're going to populate it with options after the server responds to our request. We'll add a button to click as well that runs our function:
<input type="button" onClick="populate();" value="Ajax GO!" />
And finally, the populate function goes in our Javascript:
function populate()
{
new Ajax.Request('genres.php',
{
onSuccess: function(trans)
{
var response = trans.responseText.evalJSON();
for (var i=0; i<response.genres.length; i++)
$('genre').options[i] = new Option(response.genres[i],response.genres[i]);
},
onFailure: function(trans) { alert('An error occurred: '+trans.statusText); }
});
}
The above function makes an Ajax request to the url genres.php and on getting the response it runs the onSuccess function. This function decodes the JSON response and then loops through each item adding it to the select box.

As for the server part, the bit that returns the genres, this is simply:
<?php
echo json_encode(array('genres'=>array(
'Blues',
'Country',
'Funk',
'Jazz',
'Pop',
'Rock'
)));
?>
In addition to the above you must actually load the prototype.js library. Take a look at the source of the above in action to see how it hangs together.

Custom Search