JavaScript : Ajax

Ajax stands for Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. It can send as well as receive information in a variety of formats, including JSON, XML, HTML, and even text files.

The keystone of AJAX is the XMLHttpRequest object. All modern browsers support the XMLHttpRequest object (IE5 and IE6 use an ActiveXObject).  After getting this object , you need to decide what you want to do after you receive the server response to your request. At this stage, you just need to tell the HTTP request object which JavaScript function will handle processing the response. This is done by setting the onreadystatechange property of the object to the name of the JavaScript function that should be called when the state of the request changes, like this:

httpRequest.onreadystatechange = functionToHandleResponse;

Note that there are no parentheses after the function name and no parameters passed, because you’re simply assigning a reference to the function, rather than actually calling it. Also, instead of giving a function name, you can use the JavaScript technique of defining functions on the fly (called “anonymous functions”) and define the actions that will process the response right away, like this:

httpRequest.onreadystatechange = function(){ // process the server response };

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:

httpRequest.open(“GET”,”ajax_info.txt”,true);
httpRequest.send();
The first parameter of the call t0 open() is the HTTP request method – GET, POST, HEAD or any other method you want to use and that is supported by your server. Keep the method capitalized as per the HTTP standard; otherwise some browsers (like Firefox) might not process the request. For more information on the possible HTTP request methods you can check the W3C specs.

  • The second parameter is the URL of the page you’re requesting. As a security feature, you cannot call pages on 3rd-party domains. Be sure to use the exact domain name on all of your pages or you will get a “permission denied” error when you call open(). A common pitfall is accessing your site by domain.tld, but attempting to call pages with http://www.domain.tld. If you really need to send a request to another domain, see HTTP access control.
  • The optional third parameter sets whether the request is asynchronous. If TRUE (the default), the execution of the JavaScript function will continue while the response of the server has not yet arrived. This is the A in AJAX.
  • send(string) – Sends the request off to the server. string: Only used for POST requests else null.

Remember the ‘functionToHandleResponse‘ setted for httpRequest.onreadystatechange. Let’s see what this function should do. First, the function needs to check for the state of the request. If the state has the value of 4, that means that the full server response has been received and it’s OK for you to continue processing it.

if (httpRequest.readyState === 4) {

// everything is good, the response is received }
else {
// still not ready }

The onreadystatechange event is triggered every time the readyState changes. The readyState property holds the status of the XMLHttpRequest. Three important properties of the XMLHttpRequest object:

Property Description
onreadystatechange Stores a function (or the name of a function) to be called automatically each time the readyState property changes
readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: “OK”
404: Page not found etc.

A server processes an http request and sends out a response. The response comprises a header block, a blank line, and (in most cases) a data block. The first line of the header includes a response code which indicates the success or otherwise of the request – a 3 digit number in the following ranges:

  • 200 and up – success; expect good data to follow
  • 300 and up – good request but only headers (no data). e.g. page has moved
  • 400 and up – error in request. e.g. request was for missing page (404)
  • 500 and up – error in handling request. e.g. program on server has syntax error

Now after you’ve checked the state of the request and the HTTP status code of the response, it’s up to you to do whatever you want with the data the server has sent to you. You have two options to access that data:

  • httpRequest.responseText – returns the server response as a string of text
  • httpRequest.responseXML – returns the response as an XMLDocument object you can traverse using the JavaScript DOM functions

Note that the steps above are only valid if you used an asynchronous request (third parameter of open() as set to true). If you used an synchronous request you don’t need to specify a function, you can access the data return by the server right after calling send(), because the script will stop and wait for the server answer.

Lets see this by an example. In many registration pages, user is asked to have a username for them for future logins. The username is sometimes not available. Lets check the availability using ajax. We would be creating a servlet at the server to handle request.  CheckUserNameServlet.java


package mynotes.js.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckUserNameServlet extends HttpServlet{

String[] usernames={"jane","jake","sam"};
boolean isPresent=false;
String message;

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
isPresent=false;
String input=request.getParameter("username");
System.out.println(input);

for (int i = 0; i < usernames.length; i++) {
if(usernames[i].equalsIgnoreCase(input)){
isPresent=true;
break;
}
}
System.out.println(isPresent);
if(isPresent){
message="Username is not available";
}else{
message="Username is available";
}
// Set response content type
response.setContentType("text/html");

// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println(message);
}

}

As you can see if the input is any of the values in String[] usernames, boolean isPresent will be true and ‘Username is not available’ will be returned. Mapping this servlet in web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>MyNotes_JavaScript</display-name>

<servlet>
<servlet-name>CheckUserName</servlet-name>
<servlet-class>mynotes.js.servlets.CheckUserNameServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>CheckUserName</servlet-name>
<url-pattern>/CheckUserName</url-pattern>
</servlet-mapping>
</web-app>

checkUsernameUsingGet.html


<!DOCTYPE html>
<html>
<head>
<title>Ajax</title>
</head>
<body>
<table>
<tr>
<td>Username: </td>
<td><input type="text" id="username" /></td>
<td><input type="button" id="ajaxButton" onclick="makeRequest();return false" value="Check"/>
</td>
<td><div id="result"></div></td>
</tr>
</table>
<script type="text/javascript">

var httpRequest;
function makeRequest() {
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
}

if (!httpRequest) {
alert('Cannot create an XMLHTTP instance');
return false;
}
var url="/MyNotes_JavaScript/CheckUserName?username="+document.getElementById('username').value;
httpRequest.onreadystatechange = processResponse;
httpRequest.open('GET', url);
httpRequest.send(null);
}

function processResponse() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
document.getElementById('result').innerHTML=httpRequest.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
</script>
</body>
</html>

Notice the url, it should be on the same domail. ‘/’ will append from the domain. If you use just ‘CheckUserName’, it will try to call the current browser url except chagning the last part. (like is http://www.somedomain.co/project/pages/my.html is the current url, so it will call http://www.somedomain.co/project/pages/CheckUserName instead of callig www.somedomain.co/project/CheckUserName )

Output:

ajax_checkusername_get

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: