go to  ForumEasy.com   
JavaPro  
 
 
   Home  |  MyForum  |  FAQ  |  Archive    You are not logged in. [Login] or [Register]  
Forum Home » JavaScript » AJAX + JSP Tutorial
Email To Friend  |   Set Alert To This Topic Rewarding Points Availabe: 0 (What's this) New Topic  |   Post Reply
Author Topic: AJAX + JSP Tutorial
WebSpider
member
offline   
 
posts: 147
joined: 06/29/2006
from: Seattle, WA
  posted on: 11/10/2009 10:19:27 PM    Edit  |   Quote  |   Report 
AJAX + JSP Tutorial
What's AJAX?

AJAX stands for Asynchronous JavaScript and XML.

With AJAX, a JavaScript can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can trade data with a web server, without reloading the page.

AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.

The AJAX technique makes Internet applications smaller, faster and more user-friendly.
 Profile | Reply Points Earned: 0
WebSpider
member
offline   
 
posts: 147
joined: 06/29/2006
from: Seattle, WA
  posted on: 11/10/2009 10:19:59 PM    Edit  |   Quote  |   Report 
What's the big deal to use AJAX?

It's all about user-friendly.

Without AJAX, to get or send information from/to a database or a file on the server with traditional JavaScript, your user will have to trigger certain action like clicking the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results. Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.

With AJAX, your JavaScript communicates directly with the server, a web page can make a request to, and get a response from a web server - without reloading the page. The user can stay on the same page without noticing that scripts request pages, or send data to a server in the background.

 Profile | Reply Points Earned: 0
WebSpider
member
offline   
 
posts: 147
joined: 06/29/2006
from: Seattle, WA
  posted on: 11/10/2009 10:21:39 PM    Edit  |   Quote  |   Report 
How does AJAX work?
The keystone of AJAX is the XMLHttpRequest object (IE5 and IE6 uses ActiveXObject).

By using the XMLHttpRequest object, your JavaScript communicates directly with the server for data and asynchronously proceeds with other tasks while waiting for the response from the server.

 Profile | Reply Points Earned: 0
WebSpider
member
offline   
 
posts: 147
joined: 06/29/2006
from: Seattle, WA
  posted on: 11/10/2009 10:22:41 PM    Edit  |   Quote  |   Report 
Step 1) Create an XMLHttpRequest object
<script language="javascript">
function getXmlHttpObject()
{
    if (window.XMLHttpRequest)
    {
        // for IE7+, Firefox, Chrome, Opera, Safari
        return new XMLHttpRequest();
    }
    if (window.ActiveXObject)
    {
        // for IE6, IE5
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return null;
}
</script>

 Profile | Reply Points Earned: 0
WebSpider
member
offline   
 
posts: 147
joined: 06/29/2006
from: Seattle, WA
  posted on: 11/10/2009 10:23:33 PM    Edit  |   Quote  |   Report 
Step 2) Use XMLHttpRequest object to send the request to the target server
<script language="javascript">
    XMLHttpRequest xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", url, true);
    xmlhttp.send(null);
</script>


The open() method takes two, three, or five arguments:
      XMLHttpRequest.open(method, url [, async [, user, password]]); 


The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously or not. The fourth and fifth arguments specify the user and password for authentication if the source is protected.

The send() method takes one argument:
      XMLHttpRequest.send(content); 

If the open() method’s HTTP retrieval argument is POST, the argument should contain the form data that needs to be send to the server as the follows:
    var url = "myServer.jsp";
    xmlhttp.open("POST", url, true); 
    
    var params = "name1=value1&name2=value2";
	
    //Send the proper header information along with the request
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", params.length);
    xmlhttp.setRequestHeader("Connection", "close");
    
    // send out the request
    xmlhttp.send(params);    

If the open method’s HTTP retrieval argument is GET, simply put null.

 Profile | Reply Points Earned: 0
WebSpider
member
offline   
 
posts: 147
joined: 06/29/2006
from: Seattle, WA
  posted on: 11/10/2009 10:26:25 PM    Edit  |   Quote  |   Report 
Step 3) Design a listener as to how to respond to the response
Now that you have sent out some requests, you definitely expect some thing happend in return. Therefore, a listener has not be registered to listen to the response from the server.

xmlhttp.onreadystatechange = function()
{
   //how to proceeds with the data from server
}



The beauty of AJAX is its asynchronous nature -- the waiting for the server to response does not block the process of client. For this nature to work, certain flags need to be defined to signal the current status of the response.

Step 3) Design a listener as to how to respond to the response

Property #1: XMLHttpRequest.readyState

Possible values for the readyState property:
0 -- The request is not initialized
1 -- The request has been set up
2 -- The request has been sent
3 -- The request is in process
4 -- The request is complete



Property #2: XMLHttpRequest.responseText

The data sent back from a server can be retrieved with this property


As an example, a listener can like this:
xmlhttp.onreadystatechange=function()
{
    if(xmlhttp.readyState==4)
    {
       document.getElementById("myHook").innerHTML=xmlhttp.responseText;
       document.myForm.myName.value=xmlhttp.responseText;
    }else{
       // do some funcy thing 
    }
}

 Profile | Reply Points Earned: 0
WebSpider
member
offline   
 
posts: 147
joined: 06/29/2006
from: Seattle, WA
  posted on: 11/10/2009 10:30:59 PM    Edit  |   Quote  |   Report 
Step 4) Fire the ball
Now you just need a event to trigger the AJAX action.

<html>
<body>

<form> 

Name: <input type="text" id="myID" onkeyup="fireAJAX()" />
Suggestions: <span id="myHook">This part will be soon replaced
 by response from server.</span>

</form>

</body>
</html>


 Profile | Reply Points Earned: 0
WebSpider
member
offline   
 
posts: 147
joined: 06/29/2006
from: Seattle, WA
  posted on: 11/11/2009 01:26:02 PM    Edit  |   Quote  |   Report 
AJAX Example -- AJAX Suggest on the client side: suggest.html
Now it's time to put all above together to show how a client side AJAX application looks like. A perfect example of AJAX is Google's Suggest -- a list of hints pop up while you are typing in the Google search box. Here a very silimar example (suggest.html) is shown to demostrate how AJAX make it work behind the scene.

<html>
<head>
<title>An example to show how AJAX works</title>
</head>

<body>

<script language="javascript">

var xmlhttp

function fireAJAX(str)
{
    // avoiding bothering the server too much
    if (str.length==0)
    {
        document.getElementById("myHook").innerHTML="";
        return;
    }
    
    // get an XMLHttpRequest object
    xmlhttp = getXmlHttpObject();
    
    if(xmlhttp==null)
    {
        alert ("Your browser does not support XMLHttpRequest!");
        return;
    }

    // register the lister before sending out the request
    xmlhttp.onreadystatechange = listenerForStateChange;

    // URL to the target server for response
    var url = "suggest.jsp?s=" + str;
    url = url + "?sid=" + Math.random();   // to avoid cached results

    // send out the request
    xmlhttp.open("GET", url, true);
    xmlhttp.send(null);    
}

function listenerForStateChange()
{
    if(xmlhttp.readyState==4)
    {
       document.getElementById("myHook").innerHTML = xmlhttp.responseText;
    }else{
       // do some funcy thing 
    }
}

function getXmlHttpObject()
{
    if (window.XMLHttpRequest)
    {
        // for IE7+, Firefox, Chrome, Opera, Safari
        return new XMLHttpRequest();
    }
    if (window.ActiveXObject)
    {
        // for IE6, IE5
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return null;
}
</script>

<form> 

Name: <input type="text" onkeyup="fireAJAX(this.value);" />  
Suggestions: <span id="myHook">This part will be soon replaced 
by response from server.</span>

</form>

</body>
</html>



 Profile | Reply Points Earned: 0
WebSpider
member
offline   
 
posts: 147
joined: 06/29/2006
from: Seattle, WA
  posted on: 11/11/2009 01:34:30 PM    Edit  |   Quote  |   Report 
AJAX JSP Example -- AJAX Suggest on the server side: suggest.jsp
A server side application JSP which should answer the request from the client is shown as follows:


<%!
	// preload a list of faked names
	int size;
	String[] names;
    // ...perform one time initialization.
    // ...this method is called only once per JSP, not per request
	public void jspInit() {
	    size = 100;
	    names = new String[size];
		for(int k=0; k<size; k++){
			int len = (int)(Math.random()*10);
			if(len<5)
				len = 5;
			StringBuffer sb = new StringBuffer();
			for(int j=0; j<len; j++){
				int pos = ((int)(Math.random()*1000))%26;
				if(j==0)
					sb.append((char)(pos+65));
				else
					sb.append((char)(pos+97));
			}
			names[k] = sb.toString();
		}
    }
	
%>

<%
	
	// get the parameter from the query string
	String s = request.getParameter("s");
	if(s==null)
		s = "";
	else
		s = s.toLowerCase();
		
	// go through the name list to find all the matches	
	String hint = null;
	if(s.length()>0){
		int count = 0;
		for(int k=0; k<size; k++){
			String name = names[k].toLowerCase();
			if(name.startsWith(s)){
				count++;
				if(count==1)
					hint = names[k];
				else
					hint += ", " + names[k];
			}
		}
	}

	if(hint==null){
		out.print("no suggestion");
	}else{
		out.print(hint);		
	}
%>


 Profile | Reply Points Earned: 0

 
Powered by ForumEasy © 2003-2005, All Rights Reserved. | Privacy Policy | Terms of Use
 
Get your own forum today. It's easy and free.