Thursday, September 6, 2018

A Hype-Free Introduction to Ajax

Introduction


You've probably heard all the hype about Ajax because you've seen many products claiming to be Ajax-compliant or compliant. However, you probably have not seen a correct and simple technical explanation of what Ajax really is. This article will give you an overview of the basics of what Ajax does, without the hype that drives the product.

First of all, is Ajax new?

The truth  no. JavaScript, of which Ajax is an example and has recently received the most attention, allows interaction with a server using XML data. Ajax is possible because the main browsers now offer objects that can make independent HTTP HTTP requests. Internet Explorer 5 and later provide an XMLHTTP object, while Mozilla-based browsers provide an XMLHttpRequest object. Essentially, these two objects provide the same ability to request XML data from a server and process the data in the same way. The Ajax component on the server side can be present in any technology as long as the XML can be dynamically distributed. Any dynamic web technology, from PHP to servlets, can serve as an Ajax server.

One of the disadvantages of Javascript and Ajax is that the author of the page (the person designing the last page) is forced to develop a good amount of Javascript code that handles XMLHTTP interactions. Fortunately, JavaServer Faces (JSF) provides a solution here and makes AJAX very easy to use.

Ajax under the hood

Before discussing more detailed examples of Ajax integrated with other technologies such as JSF, it helps to understand the central Ajax architecture that plays a role in an Ajax client-server transaction.

Ajax is possible because the two main technologies exist:

• A JavaScript-enabled browser that supports XMLHTTP or XMLHttpRequest objects
• HTTP server technology that can respond in XML
Since all popular browsers support JavaScript and the required XMLHTTP request objects and can generate almost any web server technology XML (or any markup), the core Ajax technology is widely used.
An Ajax application in its simplest form is essentially a standard HTML user interface with JavaScript functions for interacting with an HTTP server that can dynamically generate XML. Any dynamic web technology, from CGIs to servlets - including JSF, as we'll see later - can serve as server-side Ajax technology.
The most important elements of an Ajax main application are:
• an HTML page with:
o   UI elements that interact with Ajax JavaScript functions
o   Javascript functions that interact with the Ajax server
• Web server technology that can handle HTTP requests and respond to XML markup.
core ajax architecture
Reviewing the key elements, we have an HTML user interface with elements such as an input field, a button or anything that can be linked to Javascript. For example, a button could fire a Javascript function when pressed, or for even more subtle usage an input field could fire a Javascript function as the user types into the field. For this you could set an onkeyup= to the value of the Javascript function to process the data in the input field. For example, the input field “searchField” will call the Javascript function lookup( ) when an onkeyup event occurs (i.e. during typing).
<input type="text" id="searchField"
size="20" onkeyup="lookup('searchField');">
In addition to responding to user interface interactions (like typing), Ajax Javascript functions they can operate independently on their own timers. (An Ajax autosave feature can be implemented using this approach.)

How to Issue an XML HTTP Request

Now that we’ve reviewed how the Ajax Javascript code can be invoked, let’s review the actual code in Javascript that can issue an XML HTTP request:
if (window.XMLHttpRequest) {
   req = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
   req = new
ActiveXObject("Microsoft.XMLHTTP");
}  
This code snippet allows both major browser families (Internet Explorer and Mozilla/Safari) to make independent HTTP requests to servers. This code first checks to see if the browser supports either of the supported XMLHTTP objects and then instantiates one.
Once an XMLHttpRequest (or Microsoft’s XMLHTTP) object has been instantiated, it can be operated on in exactly the same manner.
To initialize a connection to a server, the open method is used:
req.open("GET", url, true);
The first argument is the HTTP method ( GET or POST). The second argument is the URL of the server (or form action is using a POST) and the third argument when true denotes whether the call should be made asynchronously (The “A” in Ajax). This means that the browser can continue doing other things while the request is being fulfilled. A false value in the open method denotes a non-asynchronous or serial processing. This is not recommended, as your browser will cease operations until the response has been returned.
After initializing a connection using open, the onreadystatechange call is made (only for asynchronous calls). This registers a callback function, which will be invoked once the request is complete:
 
req.onreadystatechange = processXMLResponse;
The function processXMLResponse( ), which processes the XML response, is invoked when the request is fulfilled. A callback function can also declared inline in the onreadystatechange statement:
req.onreadystatechange = processXMLResponse() {   
// process request 
}; 
Any header content can also be specified using req.setRequestHeader. Such as:
 
req.setRequestHeader("Cookie", "someKey=true");
Once the XMLHTTP request object (req) has been fully initialized, initiating a call to the server can be done using send( ):
req.send(null); 
For GET requests, a null value or empty string “” is used.
POST requests contain a string argument with form data. They also require the Content-Type to be set in the header of the request. The following two lines show how to perform a Ajax POST request:
req.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded";  
 
 req.send("name=scott&email=stiger@foocorp.com");
The callback function, which is called once the request has been fulfilled, usually has some code to make sure the request has not error-ed out. This can be accomplished by checking the readyState as well as the overall status of the HTTP request. (A readystate of 4 means the XMLHTTP request is complete and 200 means it was a success (as opposed to 404 etc.).
function processXMLResponse() { 
  if (req.readyState == 4) { 
    if (req.status == 200) {  
     // Process the XML response  
    } 
  } 
}
Processing the XML response is done using standard Javascript DOM methods. For example, to extract the employee name from the incoming XML stream:
<employee> 
  Chris  
</employee>
You can use the following:
var name = req.responseXML.getElementsByTagName("employee")[0];
Parsing more complex XML involves iterating through the elements using code such as:
for (i=0;i<elements.length;i++) {
  for (j=0;j<elements[i].childNodes.length;j++) {
    var ElementData = elements[i].childNodes[j].firstChild.nodeValue; 
  }  
} 

Using XMLHttpRequest with HTML

Note that the XML response obtained through the XMLHttpRequest object need not always be well-formed and valid. Consequently, the Ajax server-side component can send over HTML content directly to the client. JavaScript can then retrieve the HTML content by using the req.responseText method/property, which simply retrieves the content as a string. The HTML string text can then be used in whatever fashion to alter the page. For example an HTML stream of:
<h2>Hello there!</h2>                              
<p> This is <b>HTML</b></p>
                            
could be retrieved into a string using:
var HTMLcontent = req.responseText;
and then added to a specific HTML DIV tag with id="div1".
document.getElementById("div1").innerHTML += HTMLcontent;

How JSF Enables Ajax

JSF and its component-centric architecture solves the inherent difficulties of Ajax by allowing the Javascript and the embedded Ajax “plumbing” to be completely handled by the JSF component. The JSF page author need not even be concerned about the Ajax interactions between the client and the server. They just use the Ajax enabled JSF component as any other JSF component and it just does its job, and provides a richer experience. The future of JSF and Ajax working together looks bright!




No comments:

Post a Comment

From Java 8 to Java 11

Switching from Java 8 to Java 11 is more complicated than most updates. Here are some of my notes on the process. Modules Java 9 i...