AJAX Hello World with Prototype

This article should be a great resource for anyone starting to learn AJAX programming, and we are going to make it even easier with Prototype. I will assume you know the basics in XHTML, CSS, JavaScript, and PHPÂ? even though we won’t actually use PHP. Please visit http://www.w3schools.com/ if you’re already lost at this point.

Let’s really get down to the basics. AJAX is used to deliver data from the server without refreshing the page. Thats it, thats all. Data can be in the form of a page fragment, text, or data that we process into a data array like in our previous example (creating a option list).

We will use Prototype to actually make the AJAX call because it checks to see which browser is being used and does alot of low level processing for us.
The data we want to pull from the server will be a text string “Hello World.” So lets start.

Lets create a file hello_world.html that looks like this:

Â? Â? Â? Hello World

Now lets create main HTML file and make all this work!

Listing 2.1

We are done. Well, almost. Let me walk you though what we actually did here.
LineÂ? 3:Â? We call the Prototype Framework. This should be the first JavaScript file we call because it contains all the objects required to make everything work.
LineÂ? 20: We have a span with an id ‘display_area.’ This is where we want to insert the text from the server.
Lines 7-15: Our main function that does the work.Â? We call it init, but it could be called anything.
LineÂ? 9: We create a new Ajax.Request Object.
LineÂ? 10: We tell it what file to get.
Lines 11-14: The options we pass to the object, they include the method, GET. We could also tell the server we wanted to POST and onComplete.
LineÂ? 13: What we want to do when the the object has completed its operation. We pass in a function to display the response to the display_area id using innerHTML
LineÂ? 6: We need to ‘Fire’ the event and make everything work. We observe onload on the window object and call the init function when it happens.

Thats it, We’re are done. For more info on Prototype and all the other properties, methods, and options check here.

Leave a Reply

OpenID

Anonymous