Monday, April 14, 2008

Getting into AJAX with Prototype

I've been working with PHP for about 5 or 6 years. I first got into using it while working as a Database Admin at Greenville College, trying to write a web based reporting interface for the college's student data system. I had previously been using Perl for everything CGI and PHP made working with databases a lot easier. After taking a job as a network admin at a bank, I had a lot less use for PHP. I used it when I could to 'keep my skills up' on freelance work and Bank intranet stuff. Now I had been hearing about AJAX for a couple years and knew it was something I should pick up. I tried reading a few tutorials on it and learned quickly that it was a little different between browsers and took a bunch of code to get working. All the tutorials I found were more about getting it set up rather than what you did with it. They all started with the Asynchronos JavaScript and XML bit, explained the first half and never said what to do with the XML. Well, after a little playing I put it aside for a while. I recent picked it up again and found the same old tutorials and still no luck. I asked an old co-worker of mine Dan Coulter who wrote the phpflickr class if he could give me some assistance. He pointed me to Prototype which is a JavaScript framework that makes dealing with AJAX much nicer. At first I thought it was all about the AJAX, but it isn't. It really makes JavaScript much easier to use cross-platform. First of all there is a utility function for accessing DOM elements. It looks like this

$('myelement')

This returns the element with the ID of myelement. Want to change the content of a DIV called stuff?

$('myelement').update('New Content');

even better the $$() function lets you get lists of objects like

$$('div');

Would return an array of all the div tags in your document or

$('div.myclass');

would return all divs with the class 'myclass'

But what about AJAX?

As I have learned recently AJAX is less about the acronym and more about making calls to other web pages without reloading the current page. This is where PHP & AJAX really make nice friends. With Prototype, making an AJAX call is this simple:

new Ajax.Request('mypage.php',{method:'get'});

This basically opens a call to the mypage.php page and returns the results to the browser. Now this example doesn't do anything with that result. For that you have to extend things a little, and add in the $() stuff

new Ajax.Request('mypage.php',{
method:'get',
onSuccess: function(r){
$('mydiv').update(r.responeText);
}});


This code runs the mypage.php page, takes the results of that page and replaces the contents of the element mydiv with it.

I am still digging into Prototype, and find new things to do with it each time I sit down with it. So, if you are interested in picking up AJAX or just beefing up your JavaScript programming, I would highly recommend it.

No comments: