skip to main | skip to sidebar

Monday, September 6, 2010

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) { = name;     }
    public String getEmail() {         return email;     }
    public void setEmail(String 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() + "");         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() + "");         emp.setDesignation("Designation" + empCode);         emp.setDepartment("Department" + empCode);         return emp;     } }

package com.rakesh.ex.web; 
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!");
            this.url = url;
            var el = document.getElementById(elId);
            if (!el) {
                alert("Container Element, to place Ajax response doesn't exists!");
            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!");
                var params = "empCode=" + empCode;
                // for multiple parameters separate them by '&' as given below
                // var params = "empCode=E1001&dept=TestDept"
                // this.makeGETRequest(params);
            } else
                alert("Your browser does not support AJAX.");
        }, // End of sendAjaxRequest() 
        makePOSTRequest : function (params) {   "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) {   "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" "">
<html xmlns="" xml:lang="en" lang="en">
    <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>

Download the Source code.


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 Reddy said...

Hope the following links will help

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 Reddy 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

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 Reddy 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.
-- 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.

cegon-hopes said...

hi .,
can u mail me the steps to implement this example in netbeans6.9.1 .
My mail id:

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?

Pawankumar Jajara

Rakesh Reddy 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.

Post a Comment