JavaScript Libraries

Chapter 11. Ajax

Topics in This Chapter

  • "Ajax Fundamentals" on page 530

  • "JavaScript Libraries" on page 533

  • "Form Completion" on page 534

  • "Realtime Validation" on page 537

  • "Propagating Client-Side View State" on page 542

  • "Direct Web Remoting" on page 543

  • "Ajax Components" on page 546

  • "Ajax4jsf" on page 554

Web developers have long been mired in the mundane business of form processing without the means to acheive the high level of interactivity common in desktop applications. Or so we thought. When Google unveiled Google Maps, they proved that web applications can provide rich user interfaces that are just as compelling as desktop applications.

Google Maps also set in motion an incredible wave of innovation whose effects will be felt in the software development community for some time to come. In this chapter we will see some of that innovation in action as we explore using JSF and Ajax (Asynchronous JavaScript with XMLHttpRequest) together to create rich user interfaces. Along the way, we will discuss the following topics:

  • Ajax fundamentals (page 530)

  • Implementing Ajax with a servlet in a JSF application (page 532)

  • Using JSF phase listeners for more complex Ajax scenarios (page 537)

  • Form completion (page 534) and realtime validation (page 537)

  • Accessing UI view state from an Ajax call (page 542)

  • Dealing with client-side state saving and Ajax (page 542)

  • Direct Web Remoting (page 543)

  • Wrapping Ajax in JSF components (page 546)

  • Using the Ajax4jsf framework (page 554)

Ajax Fundamentals

Ajax is a simple three-step process:

1.

Invoke a URL from JavaScript code on the client.

2.

Handle the URL on the server and write to the response.

3.

After the response is complete, integrate the response into the DOM (Document Object Model).

These steps are almost identical to what JSF does when you click a link, which illicits a request. JSF handles that request on the server by ultimately writing to the response, which overwrites the previous response.

The same applies for Ajax requests, except for the last step. In an Ajax request, we don't refresh the entire page; instead, we update only part of the page. That subtle difference lets us perform all kinds of interesting interactions that were heretofore unheard of in web applications.

To illustrate the steps in an Ajax request, we now take a look at the application shown in Figure 11-1.

Figure 11-1. Basic Ajax with an XHR object and a servlet


The application shown in Figure 11-1 performs an Ajax request to obtain the current date and time from the server. Subsequently, on the client, the application integrates that response into the web page's DOM. That causes the date to update without refreshing the entire page.

Here is how it works. First, we have a DIV, which is initially empty. After the request, we update that DIV's inner HTML. Here is the DIV and the button that sets everything in motion:

  <h:commandButton type="button"      value="#{msgs.buttonPrompt}"      onclick="showDateAndTime();"      style/>   <div  />

Notice the button's type is button, which means it is a push button and not a submit button. When a user activates that button, JSF does not submit the surrounding form; instead, it calls the JavaScript showDateAndTime function, which looks like this:

  <script type="text/javascript" language="Javascript1.1">   <!--   var xhr;   function showDateAndTime() {       sendRequest("dateAndTime.ajax", // the URL         processAjaxCall);   // the callback function   }   function sendRequest(url, handler) {      initXHR();      xhr.onreadystatechange = handler; // set callback function      xhr.open("GET", url, true); // open asynchronous GET request      xhr.send(null); // send the request without params   }   function initXHR() {      if(window.XMLHttpRequest) {  // Not a Microsoft browser         xhr = new XMLHttpRequest();      }      else if(window.ActiveXObject) { // Microsoft browser         xhr = new ActiveXObject("Microsoft.XMLHTTP");      }   }   function processAjaxCall() {      if(xhr.readyState == 4) {  // if the request is finished...         if(xhr.status == 200) { // ...and everything's okay            // Get the dateDiv DIV and configure it            // with the response text            var dateDiv = window.document.getElementById("dateDIV")            dateDiv.innerHTML = xhr.responseText;         }      }   }     

The showDateAndTime function calls sendRequest(), which locates the XMLHttpRequest object otherwise known as the XHR (XMLHttpRequest) object with the initXHR function.

Once we have the XHR object, we are ready to go. First, we set the XHR object's callback function to our own processAjaxCall() and then we open and send the request. As the Ajax call progresses, the XHR object will repeatedly invoke our callback function with news concerning the request's progress.

As it turns out in practice, folks are mostly concerned with reacting to an Ajax request after it has successfully completed, as is the case for our example. In our callback function, we check for a successful request code, named readystate == 4 and status == 200. That status code corresponds to the HTTP status, meaning that the request was handled successfully.

Once the Ajax call has successfully completed, we set the inner HTML of our DIV to the response text. That response is generated by a servlet:

  public class AjaxServlet  extends HttpServlet {       public void doGet(HttpServletRequest request, HttpServletResponse response)                 throws ServletException, IOException {           response.setContentType("text/plain");           response.setHeader("Cache-Control", "no-cache");           response.setStatus(HttpServletResponse.SC_OK);           response.getWriter().write(((new java.util.Date()).toString()));       }   }     

The preceding servlet is associated with the URL dateAndTime.ajax in the deployment descriptor, which associates all URLs that end in .ajax with the AjaxServlet.

Note

Ajax newcomers sometimes mistakenly believe that Ajax, because it provides a more responsive user interface, reduces server-side traffic. In fact, Ajax applications typically have more server-side traffic because each Ajax request involves a trip to the server. Because those requests are asynchronous, however, Ajax creates the perception of a more responsive UI, though it typically does not reduce the load on the server.




Core JavaServerT Faces
Core JavaServer(TM) Faces (2nd Edition)
ISBN: 0131738860
EAN: 2147483647
Year: 2004
Pages: 84

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net