Ajax Servlet Form Submit

Ajax Servlet Form Submit


Posted in : Java Posted on : November 8, 2011 at 7:18 PM Comments : [ 0 ]

In this tutorial you will learn about how to send / submit a form using ajax.

Ajax Servlet Form Submit

In this tutorial you will learn about how to send / submit a form using ajax.

To do so here I am giving a simple example which will demonstrate you how to submit form.

At first I create a html file named form.html into which I add the reference of JavaScript file named ajaxFrmSbmt.js. You can use the full code of JavaScript by downloading from the "simonerodriguez.com". Further I call the 'getxmlHttpRequest()' on the event 'onsubmit' in the form tag and passed the parameter values according to the variables given as the parameter of this method. Next I created a Servlet named ServletForm.java that will take the request of parameters and the response will be sent by the server. In this simple example a textarea is taken as to write the text and a checkbox is taken otherwise. When you will write the text into the textarea and whatever you do with checkbox i.e. select or deselect and click on the submit button the form will be submitted and the text of textarea and the checkbox status will be respond you without refreshing the whole page. It may be possible that the response message i.e. 'please wait...' will not be lookup due to the short responding time.

Example :

form.html

<html>
<head>
<title>Ajax Servlet Form Submit</title>
<script type="text/javascript" src="js/ajaxFrmSbmt.js">
</script>
</head>
<body>
<form name="form1" method="post" onsubmit="getxmlHttpRequest('ServletForm', 'form1', 'message', 'please wait...'); return false;">
<TEXTAREA NAME="address" ROWS=3 COLS=40></TEXTAREA><BR>
<label> <br />
<input name="checkbox" type="checkbox" id="checkbox" value="True" /> CheckBox</input><br><br>
</label>
<input type="submit" value="submit"/>
</form>
<div id="message"></div>
</body>
</html>

ajaxFrmSbmt.js

function getxmlHttpRequest(servletName,formname,responsediv,responsemsg) {
var xmlhttp = false;
var x = this;
// For the browsers Mozilla/Safari/Ie7
if (window.XMLHttpRequest) {
x.xmlhttp = new XMLHttpRequest();
}
// For the browser IE
else if (window.ActiveXObject) {
x.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
x.xmlhttp.open('POST', servletName, true);
x.xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
x.xmlhttp.onreadystatechange = function() {
if (x.xmlhttp.readyState == 4) {
updatepage(x.xmlhttp.responseText,responsediv);
}
else{
updatepage(responsemsg,responsediv);

}
}
x.xmlhttp.send(getquerystring(formname));
}

function getquerystring(formname) {
var form = document.forms[formname];
var qstr = "";

function GetElemValue(name, value) {
qstr += (qstr.length > 0 ? "&" : "")
+ escape(name).replace(/\+/g, "%2B") + "="
+ escape(value ? value : "").replace(/\+/g, "%2B");
//+ escape(value ? value : "").replace(/\n/g, "%0D");
}

var elemArray = form.elements;
for (var i = 0; i < elemArray.length; i++) {
var element = elemArray[i];
var elemType = element.type.toUpperCase();
var elemName = element.name;
if (elemName) {
if (elemType == "TEXT"
|| elemType == "TEXTAREA") 
GetElemValue(elemName, element.value);
else if (elemType == "CHECKBOX" && element.checked)
GetElemValue(elemName, 
element.value ? element.value : "On"); 
else if (elemType.indexOf("SELECT") != -1)
for (var j = 0; j < element.options.length; j++) {
var option = element.options[j];
if (option.selected)
GetElemValue(elemName,
option.value ? option.value : option.text);
}
}
}
return qstr;
}
function updatepage(str,responsediv){
document.getElementById(responsediv).innerHTML = str;
}

ServletForm.java

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;

public class ServletForm extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String textarea= request.getParameter("address");
out.println("Your Text = "+textarea+"<br>");
boolean checkbox=request.getParameter("checkbox") != null;
if(checkbox==true)
{
out.println("checkbox is checked");
}
else
{
out.println("You have not Checked the checkbox");
}
}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>ajaxWithServlet</display-name>
<servlet>
<servlet-name>ServletForm</servlet-name>
<servlet-class>ServletForm</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ServletForm</servlet-name>
<url-pattern>/ServletForm</url-pattern>
</servlet-mapping>
</web-app>

Output :

When you will execute the above example you will get the output as :

When you will enter the value into the textarea then the page will be as :

When you will click on submit button then the page will look like as :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics