6/25/10

Simple Ajax Example

Hi i have tried a very simple and basic ajax interaction . I wanted to share that with you all.

Jsp code ::


<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <style type="text/css">
 .bp_invalid {
    color:white;
    background:red;
 }
 .bp_valid {
    color:green;
 }
</style>
<script type="text/javascript">

function AJAXInteraction(url, callback) {

    var req = init();
    req.onreadystatechange = processRequest;

    function init() {
      if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
      }
    }

    function processRequest () {
      // readyState of 4 signifies request is complete
      if (req.readyState == 4) {
        // status of 200 signifies sucessful HTTP call
        if (req.status == 200) {
          if (callback) callback(req.responseXML);
        }
      }
    }

    this.doGet = function() {
      req.open("GET", url, true);
      req.send(null);
    }
}

function validateUserId() {
    var target = document.getElementById("userid");
    var url = "AjaxServlet?id=" + encodeURIComponent(target.value);
    var target = document.getElementById("userid");
  
    var ajax = new AJAXInteraction(url, validateCallback);

    ajax.doGet();
}

function validateCallback(responseXML) {
   var msg = responseXML.getElementsByTagName("valid")[0].firstChild.nodeValue;
   if (msg == "false"){
       var mdiv = document.getElementById("userIdMessage");
       // set the style on the div to invalid
       mdiv.className = "bp_invalid";
       mdiv.innerHTML = "Invalid User Id";
       var submitBtn = document.getElementById("submit_btn");
       submitBtn.disabled = true;
    } else {
       var mdiv = document.getElementById("userIdMessage");
       // set the style on the div to valid
       mdiv.className = "bp_valid";
       mdiv.innerHTML = "Valid User Id";
       var submitBtn = document.getElementById("submit_btn");
       submitBtn.disabled = false;
    }
}
</script>

 <title>Form Data Validation using AJAX</title>

</head>

 <body>

<script type="javascript">
   function disable()
   {
       var target = document.getElementById("submit_btn");
       target.disabled=true;
   }

</script>
  <form name="updateAccount"  method="post">
   <input type="hidden" name="action" value="create"/>
   <table border="0" cellpadding="5" cellspacing="0">

    <tr>
     <td><b>User Id:</b></td>
     <td>
      <input    type="text"
                size="20"
                  id="userid"
name="id"
                autocomplete="off"
             onkeyup="validateUserId()">
     </td>
     <td>
      <div id="userIdMessage"></div>
     </td>

    </tr>
    <tr>
     <td align="right" colspan="2">
      <input id="submit_btn" type="Submit" disabled="true"  value="Create Account">
     </td>
     <td></td>
</tr>
   </table>
  </form>

</body>
</html>


Ajax servlet Code ::


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author toyopet
 */
public class AjaxServlet extends HttpServlet {
 
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
         response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet AjaxServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet AjaxServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
            */
             String targetId = request.getParameter("id");
            if ((targetId != null) && (targetId.equalsIgnoreCase("admin"))) {
                System.out.println("inside if");
                response.getWriter().write("<valid>true</valid>");


            } else {

                response.getWriter().write("<valid>false</valid>");

            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

No comments:

Post a Comment

Popular Posts