Overview of AJAX:
AJAX or Asynchronous JavaScript and XML are a set of web development technologies for creating interactive web applications. Combinations of following technologies help web
Developers to bring rich user experience to the application user:
• HTML and CSS for presenting information.
• JavaScript and XML DOM (Document Object Model) to dynamically display and interact with the information.
• XMLHTTPRequest and XML to interchange and manipulate data asynchronously with the web server (Although AJAX applications can use other technologies like preformatted HTML, plain text, JavaScript as alternative to XML).
NOTE:
* Static HTML pages can asynchronously make call to the server from which it is loaded by using JavaScript technology and XMLHTTPRequest object. This call returns back XML document to the client. On the client side JavaScript can use this XML document to update or modify the Document Object Model of HTML page.
* The HTML pages interact with the JavaScript based on events such as mouse over, click, etc. to fetch the required data from the server instead of reloading the complete web page every time the change is needed to be displayed.
The key goal of AJAX based Applications:
The Real goal is to decompose jarring transitions that download
the entire new web page into a series of smaller more frequent transactions. The asynchronous background process can update the data without interrupting the user. Application component can poll for XMLHTTPRequest object’s readystate=loaded event to
notify data extracting component notifying download operation is complete.
XMLHTTPRequest Object
1) XMLHTTPRequest object allows client side JavaScript to make synchronous or asynchronous calls to the server side components (HTTP GET/POST requests). Though the name consists of XML, this object can
be used for interchanging the data formats.
2) Most of the Web Browser supports this. As of today this object is supported in IE 5.0+, Safari 1.2, Mozilla 1.0, Firefox and Netscape 7..etc.
3) This object is not a standard W3C standard. W3C DOM Level 3 ‘Load and Save’ specification contains similar functionality but none of the browser has supported it. So to make a call from browser to the server, the only way is to use XMLHTTPRequest object.
4) To create an XMLHTTPRequest object
o For Mozilla, Safari, Firefox and Netscape
var xmlhttp=new XMLHttpRequest();
o For Internet Explorer
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
5) Methods supported by this object
Method Description
abort() Cancels the current request
getAllResponseHeaders() Returns the complete set of http headers as a string
Returns the complete set of http headers as a string Returns the complete set of http headers as a string
open("method","URL",async,"uname","pswd") Specifies the method, URL, and other optional
attributes of a request
The method parameter can have a value of "GET",
"POST", or "PUT" (use "GET" when requesting data
and use "POST" when sending data
The URL parameter may be either a relative or
complete URL.
The async parameter specifies whether the request
should be handled asynchronously or not. true means
that script processing carries on after the send()
method, without waiting for a response. false means
that the script waits for a response before continuing
script processing
send(content) Sends the request
setRequestHeader("label","value") Adds a label/value pair to the http header to be sent
6) Properties What this Object have:
Property Description
onreadystatechange An event handler for an event that fires at every state change
readyState Returns the state of the object:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
responseText Returns the response as a string
responseXML Returns the response as XML
Status Returns the status as a number (e.g. 404 for "Not Found")
statusText Returns the status as a string (e.g. "Not Found" or "OK")
7) It transmits cookies with its requests just like normal requests from browser.
8)Request made with this object does not modify browser’s history states. That means clicking on back button of the browser will not display the previous pages.
9)When the XMLHTTPRequest object is used in asynchronous mode, JavaScript code needs to poll or get
notified when the call is complete. This object provides facility for callback mechanism.
**************Example on Localhost**************************
AJAX Strengths
• Rich user interface and user experiences
• Based on standard matured technologies
• Real time validation of user entered information is possible
• Suggestions and prompts to help users are possible
• No need to fetch complete set of data to the client in single trip. On selecting master data, corresponding client information can be fetched asynchronously
• Real time data fetch like address details, stock quotes, inventory details is possible without interrupting the application user
• Since the information exchange is in small pockets, there is performance improvement in overall application behavior
• Relatively easy to implement. Few OSS/Commercial frameworks are already available. As it becomes more popular, there will be more choice
• As major industry players are showing interest in this technology there are chances that in near future, there will be supporting tools and technologies
AJAX Limitations
• Not all the browsers support XMLHTTPRequest object. It means the application developed may not be accessible for older versions of browsers
• There are discrepancies in supporting the JavaScript by different browsers. The way IE creates the XMLHTTPRequest object is different than the other browsers
• AJAX based application users do not quickly understand what action they need to take on click of button or link. They are accustomed to form submit and wait for response kind of applications. When they see no page being refreshed they get
confused. Visual clue on what is going on background is needed
• Since AJAX does not maintain the browser history, back button does not work in these applications. Users expect website like functionality on these applications.
• AJAX is best used in applications to update small portions of the page in asynchronous way. Application user may not understand what has changed on the screen after he clicked on button or link. Some sort of indication (blinking text or some other indication) is must
• AJAX Engine needs to be downloaded on the client side when the session is initiated. Depending on the size of engine and network bandwidth, user may find delays in starting the application
• Debugging JavaScript based huge code is tedious
• Since the page updates are occurring asynchronously, it is difficult to keep track of overall application context.
• AJAX based applications uses too much of JavaScript and sometimes if not managed properly are difficult to debug. In addition to browsers compatibility, those are needed to be tested for asynchronous behaviors
• No standard tools available for development and debugging
•AJAX engine source code is easily viewable on client browsers
• Though ‘X’ in AJAX stands for XML, there is no standardized format (XML/JavaScript/Plain Text, etc) for fetching information back from server.
• The underlying technology and platform for AJAX applications is the same as that for non-AJAX web applications, so the underlying security holes are the same for both of the applications. But since AJAX itself is maturing, more care needs to be taken to understand how asynchronous behavior works and how exactly client-server RPC works. In some cases it is highly possible to overlook some of the issues. Some of the more common cases related to security include:
o Quick & dirty RPC mechanisms that allow arbitrary code execution on the server (For example the bug in CPAINT AJAX toolkit affected many sites recently)
o Client-side script injection to destroy server side function if not blocked in component HTML renderers
o Overly-permissive proxies that allow arbitrary cross-domain scripting
o What's more, JavaScript code is not compiled the way languages such as C and Java are. And end-user can view or even edit the JavaScript code before it runs. For example, an attacker could search for strings of text containing SQL instructions and replace that code with different queries that retrieve different information from the server.
Caution
Only Internet Explorer has provided undistorted view.
AJAX is not suitable in situations
• If your application need to support wide range of browsers. Since AJAX is maturing in terms of support for XMLHTTPRequest, JavaScript discrepancies,etc, it is advisable not to consider this technology until the browsers support is improved.
• If your application need high end graphics support for UI, AJAX is not suitable.
• When the application needs extensive ‘back’ and ‘forward’ buttons, AJAX is not good choice as AJAX does not support back button functionality. Traditionally back button is being used for navigation on web sites. Application user needs to
educate that there is difference between web site and web application. On web application navigation flow should be only through application specific links/buttons.
NOTE:
Returning to the previous state is not possible when a page is updated dynamically, since browsers typically record only static page visits in their history lists. The distinction between a static page, loaded in its entirety, and a page which has been modified dynamically might be a subtle one; users generally expect that clicking the back button in web applications will undo their last change and in Ajax applications this might not be the case as there is no static pages developed for an AJAX requests.
There are few open source AJAX related frameworks like dojo.org which are working on removing this bottleneck from AJAX functionality by allowing tracking of Ajax requests via callbacks which are called whenever the back button is pressed, restoring the application state that existed at the time.
SAMPLE CODE
JSP FILE: JavaScript from Where You starts the AJAX
function AjaxEx (Data) {
var f = document.forms[0];
if (f.feild == null)
return;
// Above code is Basic of Script not AJAX….
var req;
var url;
if (window.XMLHttpRequest) // For other Browser
{
req = new XMLHttpRequest();
}
else if (window.ActiveXObject) // For IE Browser
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "/servlet/pkg.GenericAjaxHandler";
// same how we used in Form Tag for action….
req.open("POST", url, false);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var reqString = null;
reqString = "genAjaxKey=ab&fieldName="+Data;
// Setting key and Data into request String….
req.send(reqString);
var messageObj = req.responseXML.getElementsByTagName("message")[0];
if(messageObj && messageObj.childNodes[0])
var RetrnValue = messageObj.childNodes[0].nodeValue;
if(RetrnValue==”Ajax”)
alert(“ I have done It”);
}
SERVLET FILE: Who handle’s Request and Response
public class GenericAjaxHandler extends HttpServlet {
public void init() {
// Log File Info……
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
// Pass to Post Method…….
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//The real method
key = req.getParameter("genAjaxKey");
if (key != null) {
try {
if (key.charAt(0) == 'a')
switch(key.charAt(1)) {
case 'd':
Method (req, resp);
break;
case 'b':
Method1(req, resp);
break;
}
} catch(Exception ex) {
log.out("EXP : " + ex.getMessage());
log.out("Request Failed");
}
return;
}
// Key is used to find out Which class and method to call for
// This request this functionality help Developer to have …
// Minimum handle class for AJAX in Application and search of
// Particular class/method is fast.
}
private void Method1(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String Data= req.getParameter("fieldName");
String name =Util.DataRet(Data);
String status = "
this.writeResponse(resp, status);
}
public void writeResponse(HttpServletResponse resp,
String output) throws IOException {
resp.setContentType("text/xml");
resp.setHeader("Cache-Control", "no-cache");
resp.getWriter().write(output);
}
}
JAVA FILE: Where code logic for Method who deal’s with Data
public class Util {
Util(){ }
public static String[]DataRet (String code)
{
try{
String script= “select name from emp where emp_grp_code=’”+code”’”;
// create connection
// Run the Script…
// return the data…..
} catch(Exception ex)
{
// Print Log
}finally{
// Connection closed….}}}
SPECIAL THANKS TO:
KUMARASAMY MANI , RAMA S KRISHNA
kumarasamy.mani@gmail.com mail2ramas@gmail.com
Document Editor:
DEWENDRA K PANDEY
dewendra1@gmail.com
Mob: +91-9986121093
“Best way of Learning is sharing of Knowledge”
.
hey you...go and remove csmip.....
ReplyDelete