How to Call a servlet from HTML using Ajax

    1
    24
    Spread the love
    • 1
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      1
      Share

    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.
    Regds,
    Ashwin

    Hi Ashwin,
    Please visit this link to understand more on this call http://www.hiteshagrawal.com/ajax/ajax-programming-with-jsp-and-servlets

    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-

    <html>
    <head>
    <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 userIn=document.myForm.id.value;
      var pwd=document.myForm.pwd.value;
      alert(userIn);
      if(xmlhttp) {
        xmlhttp.open(“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
           document.getElementById(“text”).innerHTML=xmlhttp.responseText;
         }
         else {
            alert(“Error during AJAX call. Please try again”);
         }
       }
    }
    </script>
            <body>
            <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” />
            </form>
            </body>
            </head>
            </html>

    Server side servlet will be something

    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    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 {
            super.init(config);
        }

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

        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);
                    }
                    else
                    out.println(“This is not a valid login” + name);
                   }
    }

    Don't miss out!
    Subscribe To Newsletter

    Receive top technical news, lesson ideas, travel tips and more!

    Invalid email address
    Give it a try. You can unsubscribe at any time.

    Spread the love
    • 1
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      1
      Share

    1 COMMENT

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here