Home | Projects | Tutorials | Articles | live chat | Submit Project | Big Vote
 
Ajax Projects
.NET Frameworks
Java Frameworks
PHP Frameworks
Ruby Frameworks
Other Frameworks
Cool AJAX sites
Ajax Resources
Ajax Tools
JavaScript frameworks
Partners

 Home /  Tutorials / HTTP Form POST Request using AJAX and Servlet

HTTP Form POST Request using AJAX and Servlet





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.

Read The Full Tutorial.
































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);
 }

source: hiteshagrawal

Says:
Fri Feb 13, 2009 12:01 pm
john Says:
Tue Feb 17, 2009 9:47 pm
This codes do not work. Something wrong. U must not post codes who did not work.
fathul Says:
Mon Mar 02, 2009 7:47 am
I agree with john... U must have mistyped
x Says:
Thu Apr 23, 2009 9:34 am
vc
Says:
Mon May 04, 2009 6:30 am
Binod Suman Says:
Sat May 09, 2009 8:24 pm

I have written one simple Ajax program using servlet response. I searched a lot over net, but couldnt get any easy example. So, I have posted that
simple ajax program at my blog.

http://binodsuman.blogspot.com/2009/05/get-start-with-ajax-ajax-siimple.html

Thanks,
Binod Suman
http://binodsuman.blogspot.com
Says:
Wed May 27, 2009 11:48 am
Richard Gathogo Says:
Mon Jul 06, 2009 10:57 am
Thanks so much for the tutorial.Can you send me the complete copy because this is not complete.
prudhvi Says:
Thu Nov 12, 2009 4:57 am
Actually This code is fine, Except threre is a small mistake in the method handleServerResponse().

document.myForm.message.innerHTML=xmlhttp.responseText;

replace the above code with the follwoing... , it'll work

document.getElementById("message").innerHTML=xmlhttp.responseText;
chjh Says:
Mon Nov 16, 2009 6:01 pm
kga Says:
Thu Dec 03, 2009 8:54 am
Thanks so much for thsi codes! Its works fine! Thats great! I found at last....
gs Says:
Sat Dec 05, 2009 1:58 pm
All code is working is fine only problem in (document.myForm.message.innerHTML=xmlhttp.responseText;)
RBK Says:
Wed Dec 30, 2009 10:55 am
thanks a lot.
Code is working require minor change
who want direct copy paste they can post a comment like above.
finally i got it thanks man
doctorate degree Says:
Wed Jan 27, 2010 6:21 am
most big companies would not go for it because of that reason...
Masters degree Says:
Wed Jan 27, 2010 6:22 am
Everything is very open and very clear explanation of issues. was truly information. Your website is very useful. Thanks for sharing.
Online Criminal Justice degree Says:
Wed Jan 27, 2010 6:22 am
most big companies would not go for it because of that reason...
Online health science degree Says:
Wed Jan 27, 2010 6:22 am
Atricore Identity Bus is designed to integrate with existing enterprise identity management infrastructures. Single sign-on agents are included for WebSphere, BEA WebLogic, JBoss, and others. It provides a pluggable architecture and multiple deployment configurations.
Law School Says:
Wed Jan 27, 2010 6:22 am
There are two new parameters (enableJsonp and jsonpCallbackParameter) which are important for our current discussion. We didnط£آ¢أ¢â€'آ¬أ¢â€‍آ¢t set the enableJsonp parameter to true because, internally, the invoke method will compare the URL with the current domain and will default to JSONP when it detects a request to a different domain.

Leave Your Comment

Name (Required)
Mail (will not be published) (required)
Website
AddThis Social Bookmark Button
Top Projects
MSN Web Messenger
MessengerFX
ebuddy
e-messenger
ILoveIM
AJAX file upload
You Tube
KoolIM.com
Meebo
Ajax.NET Professional
Tutorials
Java - How to use Ajax in JSP
Using PageMethods and JSON in ASP.NET AJAX
AJAX Design Patterns
Rasmus 30 second AJAX Tutorial
Intro to WCF for Ajax
Introduction to GWT Remote Procedure Calls
Ajax tab control using CSS
Communicate with Flash
Some thoughts on ASP.NET AJAX Roadmap
Create a Slick and Accessible Slideshow Using jQuery