How to Call a servlet from HTML using Ajax

This section is dedicated to my viewers.Here they can ask question and I will be happy to help or redirect to some page what is best suitable for them.

 Reader's Question:
Hi Animesh,
can you please let me know how to connect a servlet /jsp from HTML? Basically my requirement is something that I need to send some data to the server and get response from server without  refreshing the page.

Hi Ashwin,
Please visit this link to understand more on this call

For more simplification I am modifying the code given there
say I have a simple HTML page where user gives login id and password. upon correct login info it will say "successfull login" or else it will say " Please insert correct data"

your HTML will look like-

<title>Checking login in AJAX</title>
<script type="text/javascript">
 function getXMLObject()  //XML OBJECT
 //Not changing his original values
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() {
  //get the values from textboxes
  var pwd=document.myForm.pwd.value;
  if(xmlhttp) {"POST","servlet1",true); //gettime will be the servlet name
    xmlhttp.onreadystatechange  = handleServerResponse;
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    //send them to server one by one .You can send more data one by one..I customized this part
  xmlhttp.send("id=" + userIn);
    xmlhttp.send("pwd=" + pwd);

function handleServerResponse() {
   if (xmlhttp.readyState == 4) {
     if(xmlhttp.status == 200) {
       //document.myForm.time.value=xmlhttp.responseText; //Update the HTML Form element
     else {
        alert("Error during AJAX call. Please try again");
        <form name="myForm" method="POST" action="Servlet1">
        Enter your ID<input type="text" name="id" />
        <br />
        Enter your Password<input type="text" name="pwd" />
        <input type="button" onClick="javascript:ajaxFunction();" value="Click to check teh userName"/>
        <br />
        <div id="text" name="validation" />
Server side servlet will be something

import javax.servlet.*;
import javax.servlet.http.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Servlet1 extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

    public void init(ServletConfig config) throws ServletException {

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException,
                                                           IOException {

    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
                    PrintWriter out = response.getWriter();
                String name = null;
                String pwd=null;
                if(request.getParameter("id") != null) {
                                        name = request.getParameter("id");
                                else {
                                       name = "";
               //put your logic here
                if (name.equals("Animesh"))
                       //based on the logic send response back
                                out.println("You have successfully logged in:" + name);
                out.println("This is not a valid login" + name);

How to Call a servlet from HTML using Ajax How to Call a servlet from HTML using Ajax Reviewed by Animesh Chatterjee on January 09, 2012 Rating: 5

1 comment:

Powered by Blogger.