Ajax (asynchronous JavaScript and XML), or AJAX, is a group of interrelated web development techniques used for creating interactive web applications or rich Internet applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. Data is retrieved using the XMLHttpRequest object or through the use of Remote Scripting in browsers that do not support it. Despite the name, the use of JavaScript, XML, or its asynchronous use is not required.
The term Ajax has come to represent a broad group of web technologies that can be used to implement a web application that communicates with a server in the background, without interfering with the current state of the page. In the article that coined the term Ajax, Jesse James Garrett explained that it refers specifically to these technologies:
XHTML and CSS for presentation
the Document Object Model for dynamic display of and interaction with data
XML and XSLT for the interchange and manipulation of data, respectively
the XMLHttpRequest object for asynchronous communication
JavaScript to bring these technologies together
Since then, however, there have been a number of developments in the technologies used in an Ajax application, and the definition of the term Ajax. In particular, it has been noted that:
JavaScript is not the only client-side scripting language that can be used for implementing an Ajax application. Other languages such as VBScript are also capable of the required functionality.
the XMLHttpRequest object is not necessary for asynchronous communication. It has been noted that IFrames are capable of the same effect.
XML is not required for data interchange and therefore XSLT is not required for the manipulation of data. JavaScript Object Notation (JSON) is often used as an alternative format for data interchange, although other formats such as preformatted HTML or plain text can also be used.
Advantages
In many cases, the pages on a website consist of much content that is common between them. Using traditional methods, that content would have to be reloaded on every request. However, using Ajax, a web application can request only the content that needs to be updated, thus drastically reducing bandwidth usage.
The use of asynchronous requests allows the client's Web browser UI to be more interactive and to respond quickly to inputs, and sections of pages can also be reloaded individually. Users may perceive the application to be faster or more responsive, even if the application has not changed on the server side.
The use of Ajax can reduce connections to the server, since scripts and style sheets only have to be requested once.
Disadvantages
Dynamically created pages do not register themselves with the browser's history engine, so clicking the browser's "back" button would not return the user to an earlier state of the Ajax-enabled page, but would instead return them to the last page visited before it. Workarounds include the use of invisible IFrames to trigger changes in the browser's history and changing the anchor portion of the URL (following a #) when AJAX is run and monitoring it for changes.
Dynamic Web page updates also make it difficult for a user to bookmark a particular state of the application. Solutions to this problem exist, many of which use the URL fragment identifier (the portion of a URL after the '#') to keep track of, and allow users to return to, the application in a given state.
Because most web crawlers do not execute JavaScript code, web applications should provide an alternative means of accessing the content that would normally be retrieved with Ajax, to allow search engines to index it.
Any user whose browser does not support Ajax or JavaScript, or simply has JavaScript disabled, will not be able to use its functionality. Similarly, devices such as mobile phones, PDAs, and screen readers may not have support for JavaScript or the XMLHttpRequest object. Also, screen readers that are able to use Ajax may not properly read the dynamically generated content.
The same origin policy prevents Ajax from being used across domains, although the W3C has a draft that would enable this functionality.
Lets develop a login application using Ajax. This login application first authenticates a user, it asks for a login name and password (Both the login name and password is "Admin"). It displays a welcome page, when both fields are correctly filled by the user. Otherwise it shows an error and DEBUG message (Authentication Failure).
Procedure for working struts2 with ajax is same as specified in struts2 Sample page. Changes will be occur in jsp files only.
LoginAction.java
package
demo;
import
com.opensymphony.xwork2.ActionSupport;
public
class LoginAction extends ActionSupport
{
private static final long serialVersionUID = 1L; private String userName; private String password; public String Login() throws Exception
{
if(getUserName().equals("Admin") && getPassword().equals("Admin"))
{
return SUCCESS;
}
if(!getUserName().equals("Admin") || !getPassword().equals("Admin"))
{
return ERROR;
}
return NONE;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName = userName;
}
}
AjaxLogin.jsp
<html>
<head>
<script language="javascript" type="text/javascript">
function ajaxFunction()
{
var ajaxRequest; // The variable that makes Ajax possible!
//alert("hello");
if ( Number(document.all.name.value.length) <= 0 || Number(document.all.pwd.value.length) <= 0)
{
alert("Please fill the missing text fields!");
return;
}
try
{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
//alert(ajaxRequest.responseText );
document.all.resultRow.innerHTML =ajaxRequest.responseText ;
//document.all.loginStatus.style.color = "GREEN";
}
}
ajaxRequest.open("GET", "../authenticate.action?userName="+document.all.name.value+"&password="+document.all.pwd.value, true);
ajaxRequest.send(null);
}
</script>
</head>
<body bgcolor="aliceblue">
<table border=1 cellspacing="0" cellpadding="0" width="50%" height="50%" align="center">
<tr>
<td>
LOGIN
</td>
</tr>
<tr>
<td>
Your UserName Please!
<input type=text id=name name="userName">
</td>
</tr>
<tr>
<td>
Your Password Please!
<input type=text id=pwd name="password" >
</td>
</tr>
<tr>
<td>
<input type=submit id=login value="Login" align="center" onclick="ajaxFunction()">
</td>
</tr>
<tr>
<td id="resultRow">
hai
</td>
</tr>
</table>
</html>
result.jsp
<html>
<body>
<center>
<b>
<h1 style="color:blue;font-size:25px;">Authentication Successful</h1>
</b>
</center>
</body>
</html>
failure.jsp
<html>
<body>
<center>
<b>
<h1 style="color:blue;font-size:25px;">Authentication Failure</h1>
</b>
</center>
</body>
</html>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="struts2" extends="struts-default" namespace="/">
<action name="authenticate" class="demo.LoginAction" method="Login">
<result name="success">/jsp/result.jsp</result>
<result name="error">/jsp/failure.jsp</result>
<result name="none">/jsp/AjaxLogin.jsp</result>
</action>
</package>
</struts>
web.xml and build.xml are same as in Sample page.
With Ajax, we can see the difference between normal usage of struts2 and usage of struts2 with ajax. We can get quick response from server when using Ajax than using struts2 only.