• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

AJAX

What is AJAX ?

December 21, 2010 By j2eereference 2 Comments

AJAX is “Asynchronous Java Script and XML”. AJAX is a type of programming, which became popular in 2005 by Google,  Mainly used to refresh a part of a HTML/JSP  page but not the entire page.

With AJAX we can create better, faster, and more user-friendly web applications.

AJAX is based on Javascript and HTTP request .Data retrieval is commonly in the form of XML and using DOM we will parse the XML and populate the data we need.

One example for applying AJAX is Alphabet and name .In this example , We have all the alphabets in the drop down list and on select of any alphabet , the list of all the names starting with that particular alphabet will be showing in a list box.In this situation we can use  “AJAX” to send the request to back end for getting the Names list.As we are sending the request in back end and we are not waiting for the response, we can continue with another operations on the page.Using Java Script, onChange event of the alphabet  we will send the request using the XMLHTTPRequest object to a back end process to handle the request and then the response we will get as an XML, using DOM we will parse the XML and populate the data and display the names.

Filed Under: AJAX

Getting Started with AJAX

December 19, 2010 By j2eereference Leave a Comment

The most common way of using AJAX with Java technologies is to use JavaScript. You need to have AJAX functions, such as, creating an XMLHttpRequest object for your browser, then using the object requests for a JSP page or Servlet, get the response and use it in your JSP web pages.

Following are the steps to write AJAX code .

1. Create an XMLHttpRequest Object

All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

xmlhttp=new XMLHttpRequest();

Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object:

xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);

if (window.XMLHttpRequest)

  {// code for IE7+, Firefox, Chrome, Opera, Safari

  xmlhttp=new XMLHttpRequest();

  }

else

  {// code for IE6, IE5

  xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);

  }

2.Send a Request To a Server

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

xmlhttp.open(“GET”,”ajax.do “,true);

          xmlhttp.send();:

Method Description open(method,url,async) Specifies the type of request, the URL, and if the request should be handled asynchronously or not.

method: the type of request: GET or POST

          url: the location of the file on the server

          async: true (asynchronous) or false (synchronous) send(string) Sends the request off to the server.

3.The onreadystatechange event

When a request to a server is sent, we want to perform some actions based on the response.

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.0: request not initialized1: server connection established2: request received3: processing request4: request finished and response is ready
status 200: “OK”404: Page not found

In the onreadystatechange event, we specify what will happen when the server response is ready to be processed.

When readyState is 4 and status is 200, the response is ready:

AJAX Example

Bellow example is : You have a dropdown with alphabets A,B and C , On selecting any of these,  names starting with that alphabet will display in a List box.

<html>
<head>
<script language=”javascript”>
function ajaxFunction(searchkey)
{
document.myForm.matches.options.length = 0; // This is for resetting the Names List
xmlhttp = null
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest()
}
else (window.ActiveXObject)
{
xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”)
}
if(xmlhttp != null)
{
url = “AjaxServlet?key=”+searchkey;
xmlhttp.open(“GET”,url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
xmlDoc=xmlhttp.responseXML; // It could be either responseXML or responseText depends on the requirement.
x=xmlDoc.getElementsByTagName(“NAMES”)[0];
for (i=0;i<x.childNodes.length;i++)
{
var name1= x.getElementsByTagName(“NAME”)[i];
var name=(name1.childNodes[0].nodeValue) ;
document.myForm.matches.add(new Option(name,name,null));
}
}
}
} // Closing if block
else
{
alert(“Your browser does not support XMLHTTP.”)
}
} // Closing ajaxFunction
</script>
 
</head>
 
<body>
<form name=”myForm” method=get>
Select Alphabet :
<select name=”alpha” autocomplete=”off” onChange=”javascript:ajaxFunction(this.value)” >
<option value=”A”>A</option>
<option value=”B”>B</option>
<option value=”C”>C</option>
</select> <br><br>
<select multiple=yes name=”matches”></select>
</form>
</body>
</html>

Servlet example to handle AJAX call

 package com.j2eereference.ajax;

/*
 Author     :  Rakesh.B.K
 Date          :  20.12.10
 Version    :  0.1
 Name       :  AjaxServlet
 * Change History
 *
 * Date        Added By           Version Number   Description
 * —-      ————     ————–   ———–
 *
 */
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 AjaxServlet extends HttpServlet { 
 
 protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
 {
// Sets the content type to xml specific
response.setContentType(“text/xml”);
response.setHeader(“pragma”,”no-cache”);
response.setHeader(“Cache-Control”,”no-cache”);
response.setHeader(“Cache-Control”,”no-store”);
PrintWriter out = response.getWriter();         //Initializing PrintWriter
 
String searchkey=request.getparameter(“key”); 
 
if(searchkey.equals(“A”))
buffer=“<NAMES><NAME>Ann</NAME><NAME>Ajay</NAME></NAMES>”;
if(searchkey.equals(“B”))
buffer=“<NAMES><NAME>Bobit</NAME><NAME>Bharath</NAME></NAMES>”;
if(searchkey.equals(“C”))
buffer=“<NAMES><NAME>Clinton</NAME><NAME>Clay</NAME></NAMES>”;
 
out.write(buffer);
 out.flush();  
 out.close();
 }
 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
         {
            processRequest(request, response);
         }
 
}

Filed Under: AJAX

AJAX Drawbacks

December 18, 2010 By j2eereference Leave a Comment

 There are the some demerits of using AJAX.

1. Development time 

It usually requires more development time to build an application using AJAX than using other approaches.

 2. Browsing history

If you use AJAX , there wont be  any browsing history . So Back/ Forward button will be useless.

3. Cannot Bookmark the page

Data is loaded asynchronously without a page reload, so no page access is recorded in the browser history. This means that users are unable to easily bookmark or navigate to and from the application using the browser’s buttons.

4. Server load 

Server load and bandwidth can be an issue when delivering AJAX-based solutions. These solutions often use AJAX to provide features like type-ahead searching in text boxes or loading data in the background. The user may see fewer page reloads, but the server calls are still there.

5. Security 

Like any other application that uses the HTTP protocol, data is sent as clear text. For this reason, sensitive data transfer via HTTP using AJAX is not secure.

6. Javascript dependency

Another issue with AJAX is that you have to consider what to do when a user has disabled JavaScript support within their browser. This requires extra development time to deliver an alternative solution

Filed Under: AJAX

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • What is parallel Stream
  • reduce method of the Stream class
  • Difference between the findFirst() and findAny() method
  • intern() method of String class
  • SOLID – Five principles of object-oriented software design
  • Java Coding Best Practices
  • How to use lambda expression effectively
  • Enhanced pseudo-Random Number Generators in java17
  • How to use Foreign-Memory Access API
  • Pattern Matching for instanceof
  • Text Blocks – Feature added in Java17
  • Record – The new feature added in java 17
  • What is Sealed Class
  • Features added in Java 17
  • Java Buzzwords

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.