April 13th, 2009 01:37 AM
#1
Simple ajax example using java - problem while receving the response from the servlet
Hello,
I am trying learn ajax while implementing a simple ajax example using java.
Following is my index.html page where I am trying to use ajax and get some text from the servlet
and display it in the <div>.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Ajax Test Page </TITLE>
<script type="text/javascript">
function register()
{
var req;
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest( );
}
else if (window.ActiveXObject)
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "register";
req.onreadystatechange = response;
req.open("GET", url, true);
req.send(null);
}
function response()
{
if (req.readyState==4)
{
if (req.status == 200)
{
var time = req.responseText;
alert(time);
document.getElementById("register").innerHTML = req.responseText;
}
}
}
</script>
</HEAD>
<BODY>
<a href="" onClick="register();">Register</a>
<div id="register"> </div>
</BODY>
</HTML>
Following is my servlet where I am sending a text "First Name" in response to the ajax call.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RegisterForm extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
doGet(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
response.setContentType("text/html");
response.getWriter().write("First Name");
System.out.println("inside doget");
}
}
When I run this application, I can see that the request is being sent to the servlet (RegisterForm)
"System.out.println("inside doget");" is executed, "inside doget" is printed on to the Tomcat console but the response is not caught in the response() javascirpt method.
Can anyone please tell me where am I going wrong?
Tags for this Thread
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Click Here to Expand Forum to Full Width
Bookmarks