The principle for all these types of handlers is essentially the same, but they vary in some details.
Handling mouse clicks, key presses etc
To handle events that occur on specific elements of the page, such as mouse clicks and key presses, we attach an event handler to the element in question. For example, to have a function called when the user clicks on an image, we would do the following:
<img src="searchImage.gif" alt="Search" onClick="searchClicked(event);">
The event object passed into our method contains various useful properties that we might want to read as appropriate: the coordinate of a moues click, the Unicode code of a key pressed etc. Common events useful for AJAX applications include:
Usually within the event handler of a page element is where we will initiate a call to the server to fetch some data.
The onLoad hander
An onLoad() handler is typically used in an AJAX application when we need to make a call to the server to fetch the "default" data displayed when the page is first loaded. Various "AJAX-enabled" pages will therefore not need such a handler.
Handling received data/response from the server
When we make a request to the server (as mentioned, generally in response to a user mouse click etc), our program doesn't get back the data immediately. Instead, we register the function that we would like to be called some time in the future when the data is available (or if a connection error occurs etc).
This is the asynchronous bit of AJAX: rather than blocking until a response comes back from the server, our client can potentially continue to do other things in the meantime.
Making a server request from the web page and processing the corresponding data is generally the central component of an AJAX application. On the next page, we look at the XMLHttpRequest object which provides this functionality, and is where the handling to process the incoming data is registered.
Written by Neil Coffey. Copyright © Javamex UK 2008. All rights reserved.