Jonathan Snook, Aaron Gustafson, Stuart Langridge, and Dan Webb
"Accelerated DOM Scripting with Ajax, APIs, and Libraries"
Top), at the bottom of the element (Insertion.Bottom), or after the element (Insertion.After). To build a really simple chat program, there is a chat window, a text box, and a send button:
To hook up the send button, add an event observer to it, sending the contents of the msg input to the server. When the Ajax call returns, it automatically places the response at the end of the chat element. function sendMessage() { // update the chat element with the response new Ajax.Updater($('chat'), '/path/to/script', { parameters: { text: $('msg') }, insertion: Insertion.Bottom }); } // run sendMessage any time the send button is clicked Event.observe($('send'), 'click', sendMessage); Ajax.PeriodicalUpdater If you want to add server polling to the chat program, you can extend the application with the PeriodicalUpdater. As you can likely surmise, the PeriodicalUpdater will make a call to the server every X seconds and update the chat element with the response: new Ajax.PeriodicalUpdater($('chat'), '/path/to/script', { frequency: 2, /* 2 seconds */ insertion: Insertion.Bottom }); CHAPTER 5 n AJAX AND DATA EXCHANGE 125 YUI With the YUI library, everything is handled through the connection manager. Here??™s an example: var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); The first parameter tells YUI whether you are making a GET or POST request.