Form Completion

One of the prototypical Ajax use cases is form completion, where a user enters information in a field that causes other fields on the page to change. For example, we can use Ajax to react to the value entered into a Zip Code field, as shown in Figure 2.

Figure 2. Form completion (Top: User enters an unknown Zip Code. Bottom: User enters a known Zip Code.)

image

When the user leaves the Zip Code textfield, we send an Ajax request to the server, passing the current value of the Zip Code field as a request parameter. We associate the Zip Code field with the event handler like this:

image

The zipChanged function uses Prototype to send the Ajax request:

image

When the request is finished, Prototype calls the onComplete callback specified in the preceding code fragment. Here’s what that function looks like:

image

Once again, we’re using Prototype in this example, which greatly simplifies our JavaScript, mainly through the use of Prototype’s Ajax.Request object, which executes the Ajax request, and the $() function, which is a handy shortcut for window.document.getElementById().

In the preceding code fragment, we’re also using the Fade Anything Technique’s Fat JavaScript object to fade both the City and the State fields after we update them.

The URL that we used for the Ajax call—zipChanged.ajax—is handled on the server by a servlet:

image

If the servlet finds the Zip Code in our “database,” it writes a simple string to the response with this format: City, State. If we don’t find a match, we return this instead: NO DATA, NO DATA. When the request is finished, we parse that response string and set the inner HTML of the City and State textfields to their respective values. Of course, in a real application, you might opt for a more robust database of Zip Codes.


image Note: Simple Ajax interactions are easy to implement with JSF

The preceding form completion example requires very little knowledge of JSF, other than attaching JavaScript event handlers to JSF components (with DHTML attributes provided by the tags in the HTML tag library) and knowing how JSF creates client identifiers from component IDs. As that example illustrates, simple Ajax interactions can be easily implemented in a JSF application without much knowledge of JSF itself.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.27.178