hi im trying out a servlet based ajax here in my program im using a html page with button and textbox when i click the button it should fire some ajax request to the server done some computations and return result in the same page
<html>
<head>
<title></title>
</head>
<body>
<h3>Ajax in servlets</h3>
<div id="change"> hi there</div>
<input type="text" id="fname" name="solo">
<input type="button" align="center" value="Ajax" onclick="ajaxreq()" />
</body>
</html>
in this html page a text box and a button when i click on the button it should execute the following java script function
var xmlreq=null;
var a=document.getElementById("fname");
function ajaxreq(){
if(window.XMLHttpRequest){
xmlreq=new XMLHttpRequest();
}
else if(window.ActiveXObject){
xmlreq=new ActiveXObject("Microsoft.XMLHTTP");
}
try{
xmlreq.onreadystatechange=response;
xmlreq.open("GET","Servlethello?an=+a",true);
xmlreq.send();
}
catch(e){
alert("some error")
}
}
function response(){
var res=xmlreq.responseText;
document.write(res);
alert(res);
document.getElementById("change").innerHTML=res;
}
</script>
here i have created a ajax call and send the request to the servlet Servlethello
public class Servlethello extends HttpServlet {
@Override
public void doGet(HttpServletRequest req,
HttpServletResponse res)throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1>");
String a=req.getParameter(an);
out.println("solorules"+a);
out.println("</h1>");
out.close();
}
}
the variable a fetches the value entered in the textbox and send it to the servlet xmlreq.open("GET","Servlethello?an=+a",true); to this servlet
public void doGet(HttpServletRequest req,
HttpServletResponse res)throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1>");
String a=req.getParameter(an);
out.println("solorules"+a);
out.println("</h1>");
and this servlet should be displayed here hi there using this java script
var res=xmlreq.responseText;
document.write(res);
alert(res);
document.getElementById("change").innerHTML=res;