HTTP Form POST Request using AJAX and Servlet

Add a comment March 4th, 2008

In Java World Servlets are popularly used for Model View Controller(MVC) Design Pattern. This article will guide you on writing AJAX based application that will post data to Servlet and will fetching the computed data from the Servlet. With this approach the page will get the updated content from the server without refreshing the jsp/html page.

JSP Code:

<html>
<head>
<title>JSP and Servlet using AJAX</title>
<script type="text/javascript">
 
function getXMLObject()  //XML OBJECT
{
   var xmlHttp = false;
   try {
     xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")  // For Old Microsoft Browsers
   }
   catch (e) {
     try {
       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")  // For Microsoft IE 6.0+
     }
     catch (e2) {
       xmlHttp = false   // No Browser accepts the XMLHTTP Object then false
     }
   }
   if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
     xmlHttp = new XMLHttpRequest();        //For Mozilla, Opera Browsers
   }
   return xmlHttp;  // Mandatory Statement returning the ajax object created
}
 
var xmlhttp = new getXMLObject();	//xmlhttp holds the ajax object
 
function ajaxFunction() {
  if(xmlhttp) { 
  	var txtname = document.getElementById("txtname");
    xmlhttp.open("POST","getname",true); //getname will be the servlet name
    xmlhttp.onreadystatechange  = handleServerResponse;
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send("txtname=" + txtname.value); //Posting txtname to Servlet
  }
}
 
function handleServerResponse() {
   if (xmlhttp.readyState == 4) {
     if(xmlhttp.status == 200) {
       document.myForm.message.innerHTML=xmlhttp.responseText; //Update the HTML Form element 
     }
     else {
        alert("Error during AJAX call. Please try again");
     }
   }
}
</script>
<body>
<form name="myForm" method="POST" action="getname">
<table>
 <tr>
  <td>Enter Name</td>
  <td><input type="text" name="txtname" id="txtname" /></td>
 </tr>
 <tr>
  <td colspan="2"><input type="button" value="Submit"  onclick="ajaxFunction();" /></td>
 </tr> 
</table>
<div id="message"></div> 
</form>
</body>
</head>
</html>

Servlet Code

import java.io.*;
 
import java.text.*;
 
import java.util.*;
 
import javax.servlet.*;
 
import javax.servlet.http.*;
 
public class getname extends HttpServlet {
 
	public void init(ServletConfig config) throws ServletException {	
		super.init(config);
	}
 
	public void destroy() {
 
	}
 
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		String name = null;
		PrintWriter out = response.getWriter();
		if(request.getParameter("txtname") != null) {
			name = request.getParameter("txtname");
		}
                else {
                       name = "";
                }
  	        out.println("You have successfully made Ajax Call:" + name);
	}
}

Explanation for the AJAX Code

Here i have declared 3 JavaScript function:
getXMLObject() – Responsible for creating the AJAX Object depending on the browser.
ajaxFunction() – Responsible for calling servlet through AJAX call.
handleServerResponse() – Responsible for displaying the data retrieved from the server.

How the AJAX Code Works:

  • When the page loads i am creating an AJAX Object by calling the getXMLObject() function and returning the object created in the xmlhttp variable
  • When the user clicks on the input Button, ajaxFunction() gets called which checks for whether the Ajax Object is created or not and depending on that calls the remote script. Here a function handler handleServerResponse is also defined for retrieving the value from the server
  • When the readystate of the AJAX call reaches 4 and the http status is 200 we pass the data fetched from the server to the textbox

Your email:

 

Explanation for the Servlet Code

  • By default doPost function gets called when you post the content to the servlet
  • In doPost function i am fetching the POST data in the form of txtname and assigning it to the local variable name
  • Finally i am displaying the data got through POST. All the displayed data gets passed to the Ajax Object in the form of response to the Ajax call made to the servlet


Popular Articles:

Subscribe to my RSS feed.

  1. April 8th, 2008 at 04:50 | #1

    Good site I “Stumbledupon” it today and gave it a stumble for you.. looking forward to seeing what else you have..later

  2. February 19th, 2009 at 03:54 | #2
    riya

    code not working!u sue his code works…after submit servlet output not shown page remain as it is..help

  3. February 19th, 2009 at 03:55 | #3
    riya

    i have given same names and checked code properly…

  4. March 16th, 2009 at 11:05 | #4
    Ahmed

    hi the code really worked but its workin only for posting one value from the form , i have a form that posts many values from some eight text fields, this code is not working with those no of inputs please suggest a solution,
    and its urgent ive to use in my final sem project,

    thanks a lot in advance

  1. No trackbacks yet.
Comments feed

Spam protection by WP Captcha-Free