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:
<?phpecho 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.
By the way, according to the PHP website, the json_encode function is available from PHP version 5.2.0 onwards.
Alternative JSON libraries exist which you can use to encode if you’re on an earlier version of PHP (although encouraging your webhost to upgrade is a good move!). Check out http://nz2.php.net/json_encode and http://www.json.org/ for details on both.