Skip to main content

Ajax Form Submit GET/POST Methods

This example explains GET and POST methods of form submit using AJAX. Only code is posted for now, will try to update it later some time. Complete example can be downloaded using the link at the end of the post.
package com.rakesh.ex.dto; 
public class EmployeeDTO {     private String empId;     private String name, email;     private String designation, department;
    public EmployeeDTO(String empId) {         this.empId = empId;     }
    public String getEmpId() {         return empId;     }
    public void setEmpId(String empId) {         this.empId = empId;     }
    public String getName() {         return name;     }
    public void setName(String name) {         this.name = name;     }
    public String getEmail() {         return email;     }
    public void setEmail(String email) {         this.email = email;     }
    public String getDesignation() {         return designation;     }
    public void setDesignation(String designation) {         this.designation = designation;     }
    public String getDepartment() {         return department;     }
    public void setDepartment(String department) {         this.department = department;     } }

package com.rakesh.ex.dao; 
import java.util.ArrayList; import java.util.List;
import com.rakesh.ex.dto.EmployeeDTO;
public class EmployeeDAO {
    /**      * sample method to get list of employees. This method creates sample list      * of employees data.      */     public List<EmployeeDTO> getEmployees() {         List<EmployeeDTO> empList = new ArrayList<EmployeeDTO>();         for (int i=1; i<=10; i++)             empList.add(createSampleData(i, i%2));         return empList;     }
    private static EmployeeDTO createSampleData(int i, int j) {         EmployeeDTO emp = new EmployeeDTO(String.valueOf(1000 + i));         emp.setName("Employee" + i);         emp.setEmail(emp.getName() + "@company.com");         emp.setDesignation("Designation" + i);         emp.setDepartment("Department" + j);         return emp;     }
    /**      * create dummy employee information. You can replace this method to query the      * database for actual employee information in your implementation.      */     public EmployeeDTO getEmployeeInfo(String empCode) {         EmployeeDTO emp = new EmployeeDTO(empCode);         emp.setName("Employee-" + empCode);         emp.setEmail(emp.getName() + "@company.com");         emp.setDesignation("Designation" + empCode);         emp.setDepartment("Department" + empCode);         return emp;     } }

package com.rakesh.ex.web; 
import java.io.IOException;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import com.rakesh.ex.dao.EmployeeDAO; import com.rakesh.ex.dto.EmployeeDTO;

public class AjaxExample extends HttpServlet {     private static final long serialVersionUID = -6377586508833712244L;
    private EmployeeDAO empDAO;
    @Override     public void destroy() {         super.destroy();         this.empDAO = null;     }
    @Override     public void init() throws ServletException {         super.init();         this.empDAO = new EmployeeDAO();     }
    @Override     protected void doGet(HttpServletRequest req, HttpServletResponse resp)             throws ServletException, IOException {         doPost(req, resp);     }
    @Override     protected void doPost(HttpServletRequest req, HttpServletResponse resp)             throws ServletException, IOException {         final String empCode = req.getParameter("empCode");         // get employee info         EmployeeDTO empInfo = empDAO.getEmployeeInfo(empCode);         // set employee list in to request         req.setAttribute("emp_info", empInfo);
        // forward to jsp which generates table out of employee list         req.getRequestDispatcher("emp_info.jsp").forward(req, resp);         return;     }
}

<%@page import="java.util.List" %>
<%@page import="com.rakesh.ex.dto.EmployeeDTO" %>
<%
    EmployeeDTO empInfo = (EmployeeDTO) request.getAttribute("emp_info");
    if (empInfo == null) {
%>
    <p>Could not find employee information!</p>
<%    } else { %>
    <div class="data">Employee ID: <%=empInfo.getEmpId()%></div>
    <div class="data">Name        : <%=empInfo.getName()%></div>
    <div class="data">Email        : <%=empInfo.getEmail()%></div>
    <div class="data">Designation: <%=empInfo.getDesignation()%></div>
    <div class="data">Department    : <%=empInfo.getDepartment()%></div>
<% } %>

(function() {
    AjaxEx = {
        init: function(url, elId) {
            if (!url || !elId) {
                alert("Invalid input!");
                return;
            }
            this.url = url;
            var el = document.getElementById(elId);
            if (!el) {
                alert("Container Element, to place Ajax response doesn't exists!");
                return;
            }
            this.el = el;
            this.sampleHtml = "<p>This will be replaced with AJAX response!</p>";
            // create xml http request object for AJAX requests
            this.xmlHttp = this.initXmlHttp();
        }, // End of init()
        initXmlHttp : function () {
            if (window.XMLHttpRequest)
                // Firefox, Opera, IE7, etc.
                return new XMLHttpRequest();
            if (window.ActiveXObject)
                // IE6, IE5
                return new ActiveXObject("Microsoft.XMLHTTP");
        }, // End of initXmlHttp()
        resetContent : function () {
            this.el.innerHTML = this.sampleHtml;
        }, // End of resetContent()
        sendAjaxRequest : function () {
            // initialize XML Http object if not available
            if (!this.xmlHttp)
                this.xmlHttp = this.initXmlHttp();
            if (this.xmlHttp) {
                var ajaxObj = this;
                this.xmlHttp.onreadystatechange = function() {
                    if (ajaxObj.xmlHttp.readyState==4 && ajaxObj.xmlHttp.status==200) {
                        // 4 = "loaded", 200 = "OK"
                        ajaxObj.el.innerHTML = ajaxObj.xmlHttp.responseText;
                    }
                };
                var selBox = document.getElementById("empCode");
                // prepare parameters
                var empCode = selBox.options[selBox.selectedIndex].value;
                if (empCode == "") {
                    alert("Please select employee code to get employee information!");
                    return;
                }
                var params = "empCode=" + empCode;
                // for multiple parameters separate them by '&' as given below
                // var params = "empCode=E1001&dept=TestDept"
                this.makePOSTRequest(params);
                // this.makeGETRequest(params);
            } else
                alert("Your browser does not support AJAX.");
        }, // End of sendAjaxRequest() 
        makePOSTRequest : function (params) {             this.xmlHttp.open("POST", this.url, true);             //Send the proper header information along with the request             this.xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");             this.xmlHttp.setRequestHeader("Content-length", params.length);             this.xmlHttp.setRequestHeader("Connection", "close");             this.xmlHttp.send(params);         }, // End of makePOSTRequest()
        makeGETRequest : function (params) {             this.xmlHttp.open("GET", this.url + "?" + params, true);             this.xmlHttp.send(null);         } // End of makeGETRequest()
    } // End of AjaxEx })();

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> 
    <title>Simple Ajax Example</title>
    <script type="text/javascript" src="js/ajax-example.js"></script>     <style type="text/css">         body {             width: 800px;             height: 600px;         }         .top_block {             text-align: center;         }         .top_block input {             font-weight: bold;         }         .ajax_content {             border: 2px solid #000;             padding: 2em;         }         .data { margin-bottom: 0.5em; }     </style> </head> <body>     <div class="top_block">        Select Employee Code: <select id="empCode" name="empCode">             <option value="">Select</option>             <option value="E1001">E1001</option>             <option value="E1002">E1002</option>             <option value="E1003">E1003</option>             <option value="E1004">E1004</option>             <option value="E1005">E1005</option>             <option value="E1006">E1006</option>             <option value="E1007">E1007</option>         </select>         <input type="button" onclick="javascript:AjaxEx.sendAjaxRequest();" value="Get Data"/>&nbsp;&nbsp;         <input type="button" onclick="javascript:AjaxEx.resetContent();" value="Reset Content"/>     </div>     <div id="ajax_content" class="ajax_content">         <p>This will be replaced with AJAX response!</p>     </div>     <script type="text/javascript">     <!--         // view source of this page after it loads in browser         // and check this variables value         var url = "<%=request.getContextPath()%>/ajaxServlet";         AjaxEx.init(url, "ajax_content");     // -->     </script> </body> </html>

Resources:
Download the Source code.

Comments

ritu said…
Thanks for the Code.Implemented another way like on selecting the option in the list(for ex Protocol List)it displays whether the ports available or not,the same way but used onchange event.
Do you have an idea how to implement dynamic search in webpage using Ajax and JSP.
for ex: In google page if we type a character it shows all the related items from the list.
I think we hav to use Regular expression but not sure.
Any help is really appreciated.
Rakesh A said…
Hope the following links will help

http://woork.blogspot.com/2009/02/useful-ajax-auto-suggest-scripts.html

http://www.downloadjavascripts.com/Auto_Suggest.aspx
ritu said…
Hi thanks a lot 4r da reply.
sorry 4r repeated question....
How to retrieve the Hash table data with a key and multiple values.
Rakesh A said…
Well, You can use JSON object, try the following link for simple example of JSON OR XML format as response and parse it using JavaScript

http://www.json.org/example.html
ritu said…
Hi Thanks for the reply!!
Table header contains lists.
Is it possible through ajax and JSP to dynamically update only the contents of the table(not the header part)depending on the value selected in the list.

any help is really appreciated!!
Rakesh A said…
Yes, it is possible - but tricky!
But before I suggest proper solution, I'd like to know the table structure.
1. If you are displaying tabular information and you are trying refresh only table data [not the column headings], then you've to use HTML DOM to remove old 'tr' tags and create new ones by looping through the data you've received [ex. in JSON format] using AJAX.
2. If you've any other components displayed as table headers and you are displaying rest of the table content then it'll be easy try to have the following html tag structure.
table
-- tr
-- th
-- your list components
-- tr
-- td
-- div with some id

And replace the contents of the 'div' element in the second row using simple java script [innerHTML attribute], with the the data you received using AJAX.

But if you can explain the sample HTML you are using, I can make a example for you!
ritu said…
Thanks a lot for the reply.
In my case I need to go for the first option.
Due to security reasons I cant post the code here.
but I will get back to you,If I am not able to solve da issue.
if possible if there are any links for the above issue can you please post it.
Anonymous said…
hi .,
can u mail me the steps to implement this example in netbeans6.9.1 .
My mail id:
anandpremkumara@cegonsoft.org

aptamilan@gmail.com
Pawankumar said…
Hi Rakesh,
I am trying to access a JSP variable in my html file. I am able to call JSP file using AJAX but not able to access the variable after the JSP is called. Can you help me with that?

Thanks,
Pawankumar Jajara
Rakesh A said…
@Pawan: I'd love to help you solve your problem, but, It'd be nice if you show us some code of yours, you can use the 'Write Me' link to write to me.

Popular posts from this blog

Simple Accordion using Java Script and CSS

Well you can find many online, but it's difficult to find one with out any dependent API. Most of the available accordions use other APIs for animation and other stuff. For those who just want accordion with out any other stuff, this one is the perfect one. It's very simple and you don't have to be a geek to understand it. Basic knowledge of Java script and CSS will do to understand how this works. In this article I'll take you through the steps of developing an accordion. Couple of minutes you are ready to write your own. Well then let's start developing one. Layout of the HTML block looks something like the one below Lets look at the CSS first which is very simple. /** container styles **/ .ra-p, .ra-cp { padding: 0 0 0.1em; } /**** heading styles ****/ .ra-p h2, .ra-cp h2 { margin: 0px; padding: 0.2em; cursor: pointer; color: #fff; background-color: #3d80b0; } /**** collapsed heading styles ****/ .ra-cp h

Hosting Multiple Domains In Tomcat

Tomcat allows us to host multiple domains in one instance, using multiple ' Host ' tags. In this article I will explain how to do it on Tomcat. This is very simple configuration using ' Host ' tags in your server.xml . A novice can also understand this configuration very easily. Before going into the details of the configuration first lets have a look at the ' Host ' tag, ' Context ' tag and ' Alias ' tags first. <Host name="domain1" appBase="[application base]" autoDeploy="[true/false]" unpackWARs="[true/false]"> <Alias>...</Alias> <Context path="" docBase="" reloadable="[true/false]"/> </Host> First lets have a look at ' Alias ' tag. This tag is used to provide aliases for your actual domain. For example you have a domain called 'domain1.com', and you want to run the same application for 'www.do