JavaScript functions are called as the result of an event. In the case the function validate()
may be mapped to a onkeyup
event on a link or form component.
<input type="text" size="20" id="userid" name="id" οnkeyup="validate();">
The form element above will call the validate()
each time a key is pressed in the form field.
2. A XMLHttpRequest
object is created and initialized.
An XMLHttpRequest
object is initialized and configured.
var req; function validate() { var idField = document.getElementById("idField"); var url = "validate?id=" + escape(idField.value); if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } req.open("GET", url, true); req.onreadystatechange = callback; req.send(null); }
The validate()
function initializes a XMLHttpRequest
object open method requires three arguments which are with a url String of GET or POST represeting the HTTP method to be used, a String for the target URL, and a boolean indicating whether or not the call will be made asynchronously. If an interaction is set as asynchronous (true
) a callback fuction must be specfied. The callback function for this interaction is set with the statement req.onreadystatechange =callback;
. See the section titled "The XMLHttpRequest
object calls the callback()
function and processes the result" for more details.
3. The XMLHttpRequest
object makes a call.
When the statment req.send(null);
is reached the call will be made. In the case of a HTTP get this content may be null
or left blank. When the this function is called on the XMLHttpRequest
object the call to the URL that was set during the initialization of the object is called. In the case of this example the data that is posted (id
) is included as a URL parameter.
Use an HTTP GET when the request is idempotent meaning that two duplicate requests will return the same results. When using HTTP GET method the length of URL including escaped URL parameters is limited by some browsers and by server-side web containers. The HTTP POST method should be used when sending data to the server that will effect the server-side application state. A HTTP POST requires a Content-Type
header to be set on the XMLHttpRequest
object by using the following statement:
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); req.send("id=" + escape(idTextField.value));
When sending form values from JavaScript you should take into consideration the encoding of the field values. JavaScript includes an escape()
function which should be used to ensure localized content is encoded properly and that special charachters are escaped correctly.
4. The request is processed by the ValidationServlet
.
A servlet mapped to the URI "validate" checks if the user id is in the user databse or not.
A servlet processes a XMLHttpRequest
just as it would any other HTTP request. The example below show a server extracting the id
parameter from the request and validating whether or not the parameter has been taken.
public class ValidationServlet extends HttpServlet { private ServletContext context; private HashMap users = new HashMap(); public void init(ServletConfig config) throws ServletException { this.context = config.getServletContext(); users.put("greg","account data"); users.put("duke","account data"); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String targetId = request.getParameter("id"); if ((targetId != null) && !users.containsKey(targetId.trim())) { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(" valid"); } else { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(" invalid"); } } }
In this example a simple HashMap
is used to contain the users. In the case of this example let us assume the user id "duke" was submitted.
5. The ValidationServlet
returns an XML Document.
The user id "duke" is present in the list of user ids in the users HashMap
. The ValidationServlet will write a XML document to the response containing an "message" element with the value of "invalid". More complex usecases may require DOM, XSLT, or other APIs to generate the response.
response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(" invalid");
Two things that a developer needs to be aware of is that the Content-Type
is set to "text/xml" and the Cache-Control
needs to be set to "no-cache". The XMLHttpRequest
object will only process requests that are of the Content-Type
of "text/xml" and the Cache-Control
being set to "no-cache" will keep browsers from locally caching responses for cases where duplicate requests for the same URL (including URL parameters) may return different responses.