AJAX is not a new programming language, but a technique for creating better, faster, and more interactive web applications. With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can trade data with a web server, without reloading the page. AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. The AJAX technique makes Internet applications smaller, faster and more user-friendly. AJAX is a browser technology independent of web server software.
AJAX, or transmission of information through the JavaScript DOM, isn't going anywhere. Web 2.0 is clearly an exciting thing for people - even if they don't know what it is.
AJAX is based on the following web standards:
- JavaScript
- XML
- HTML
- CSS
The web standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are browser and platform independent.
AJAX is About Better Internet Applications
Web applications have many benefits over desktop applications; they can reach a larger audience, they are easier to install and support, and easier to develop. However, Internet applications are not always as "rich" and user-friendly as traditional desktop applications. With AJAX, Internet applications can be made richer and more user-friendly.
AJAX Http Requests
AJAX Uses HTTP Requests
In traditional JavaScript coding, if you want to get any information from a database or a file on the server, or send user information to a server, you will have to make an HTML form and GET or POST data to the server. The user will have to click the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results. Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly. With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object With an HTTP request, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.
The XMLHttpRequest Object
By using the XMLHttpRequest object, a web developer can update a page with data from the server after the page has loaded! AJAX was made popular in 2005 by Google (with Google Suggest). Google Suggest is using the XMLHttpRequest object to create a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions. The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7.
Common XMLHttpRequest Object Methods
Method | Description |
---|---|
abort() | Stops the current request |
getAllResponseHeaders() | Returns complete set of headers (labels and values) as a string |
getResponseHeader("headerLabel") | Returns the string value of a single header label |
open("method", "URL"[, asyncFlag[, "userName"[, "password"]]]) | Assigns destination URL, method, and other optional attributes of a pending request |
send(content) | Transmits the request, optionally with postable string or DOM object data |
setRequestHeader("label", "value") | Assigns a label/value pair to the header to be sent with a request |
Common XMLHttpRequest Object Properties
Property | Description |
---|---|
onreadystatechange | Event handler for an event that fires at every state change |
readyState | Object status integer: 0 = uninitialized 1 = loading 2 = loaded 3 = interactive 4 = complete |
responseText | String version of data returned from server process |
responseXML | DOM-compatible document object of data returned from server process |
status | Numeric code returned by server, such as 404 for "Not Found" or 200 for "OK" |
statusText | String message accompanying the status code |
AJAX Browser Support
The keystone of AJAX is the XMLHttpRequest object. Different browsers use different methods to create the XMLHttpRequest object. Internet Explorer uses an ActiveXObject, while other browsers uses the built-in JavaScript object called XMLHttpRequest.
AJAX Example
Your First AJAX Application
To understand how AJAX works, we will create a small AJAX application. First, we are going to create a standard HTML form with two text fields: username and time. The username field will be filled in by the user and the time field will be filled in using AJAX. The HTML file will be named "testAjax.htm", and it looks like this (notice that the HTML form below has no submit button!):
<html> <body> <script type="text/javascript"> function ajaxFunction() { var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } } </script> <form name="myForm"> Name: <input type="text" name="username" /> Time: <input type="text" name="time" /> </form> </body> </html> |
AJAX - The XMLHttpRequest Object
The onreadystatechange Property
After a request to the server, we need a function that can receive the data that is returned by the server. The onreadystatechange property stores the function that will process the response from a server. The following code defines an empty function and sets the onreadystatechange property at the same time:
xmlHttp.onreadystatechange=function() { // some code here } |
The readyState Property
The readyState property holds the status of the server's response. Each time the readyState changes, the onreadystatechange function will be executed.
Here are the possible values for the readyState property:
- 0 - The request is not initialized
- 1 - The request has been set up
- 2 - The request has been sent
- 3 - The request is in process
- 4 - The request is complete
xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { // some code here } } |
The responseText Property
The data sent back from the server can be retrieved with the responseText property.
xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.myForm.time.value=xmlHttp.responseText; } } |
AJAX - Request a Server
AJAX - Sending a Request to the Server
To send off a request to the server, we use the open() method and the send() method. The open() method takes three arguments. The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously. The send() method sends the request off to the server. If we assume that the HTML and JSP file are in the same directory, the code would be:
xmlHttp.open("GET","trustdir.jsp",true); xmlHttp.send(null); |
<form name="myForm"> Name: <input type="text" name="username" οnkeyup="ajaxFunction();"/> Time: <input type="text" name="time" /> </form> |
AJAX - The Server-Side Script
AJAX - The Server-Side JSP Script
Now we are going to create the script that displays the current server time. The responseText property (explained in the previous chapter) will store the data returned from the server. Here we want to send back the current time. The code in "trustdir.jsp" looks like this:
<% out.print("Now: "+new java.util.Date()); %> |
AJAX - Milliseconds to Date Java converter
Below example to convert milliseconds from January 1st 1970 to date format. Type in the text field any number:
Server side
/ajax/timestamp.jsp |
---|
<%@ page import="java.util.Date" %> <% try { String t = request.getParameter("t"); if (t==null | t.trim().length()==0) t="0"; java.util.Date dt = new Date(Long.parseLong(t)); out.print(dt.toString()); } catch (Exception e) { out.print("Invalid input"); } %> |
Client side
<html> <head> <script type="text/javascript"> var ns=(document.layers); var ie=(document.all); var w3=(document.getElementById && !ie); function GetXmlHttpObject() { var xmlHttp=null; try { xmlHttp=new XMLHttpRequest(); } catch (e) { try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } function ajaxConverter() { var xmlHttp = GetXmlHttpObject(); xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { var adDiv; if(ie) adDiv=eval('document.all.divConverter.style'); else if(ns) adDiv=eval('document.layers["divConverter"]'); else if(w3) adDiv=eval('document.getElementById("divConverter").style'); if (xmlHttp.responseText!="") { document.getElementById("divConverter").innerHTML=xmlHttp.responseText; if (ie||w3) { adDiv.visibility="visible"; adDiv.display=""; } else adDiv.visibility ="show"; } } } xmlHttp.open("GET","/ajax/timestamp.jsp?t="+document.frmConverter.t.value,true); xmlHttp.send(null); } </script> </head> <body> <form name="frmConverter"> <table> <tr> <td><input type="text" name="t" style='border:1px solid gray;font-size:13px;' value="" οnkeyup="ajaxConverter()"></td> <td><div id="divConverter" style="display:none;visibility:hidden;color:blue;font-size:13px;font-weight:bold;"></div></td> </tr> </table> </form> </body> </html> |
AJAX Disadvantages
- One big disadvantage of using AJAX is security. Often times developers do not put checks on the data coming into the server - they assume that it's coming from their own website.
- AJAX does not play well in encrypted environments. AJAX relies on plain text transmission (nothing but text can be transmitted through AJAX anyways), and so encrypted this stream and having the server-side program deal with it presents a large problem.
- Development time. Building an AJAX application from scratch is actually fairly easy, but it does take longer than building one that uses standard post-backs. As well, the developers require a fairly good knowledge of JavaScript to be able to make it usable.
Bandwidth Savings
In applications that have a significant part of each page containing content that is identical in multiple page requests, using AJAX-style methods to update only the relevant parts of a web page can bring significant bandwidth savings. Using less than 100 lines of javascript, we were able to quickly convert an existing web application to use AJAX page-update methods to drastically reduce (>60%) the bandwidth requirements of our sample application.
It is important to note that the application converted in our test was ridiculously simple. Achieving the same bandwidth reduction on a sophisticated application will likely not be as easy, if it is possible at all. However, when applied to extremely large-scale applications or applications with very tight bandwidth considerations, savings of 10% could bring a hefty cost savings.
From http://www.vicconsult.com/tips/ajax.html