Sunday 20 February 2011

JQ Forms with AJAX-JSP5

This example demonstrates the use of ajaxForm with XML data.

Sample5.jsp
-----------
<%--
Document : sample5.jsp
Created on : 19.Şub.2011, 20:38:10
Originally : belongs to "jQuery Form Plugin"
Author : Ali Riza SARAL
--%>

<%@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">
<title>JSP Page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>

<script type="text/javascript">
$(document).ready(function() {
// bind form using ajaxForm
$('#xmlForm').ajaxForm({
// dataType identifies the expected content type of the server response
dataType: 'xml',

// success identifies the function to invoke when the server response
// has been received
success: processXml
});
});
function processXml(responseXML) {
// 'responseXML' is the XML document returned by the server; we use
// jQuery to extract the content of the message node from the XML doc
var message = $('message', responseXML).text();
alert(message);
}
</script>
</head>
<body>
<div id="sample5">
<p />
This page shows how to handle XML data returned from the server.
<p />
The form below submits a message to the server and the server
echos it back in XML format.
<br />

<form id="xmlForm" action="xml-echo.jsp" method="post"><div>
Message: <input type="text" name="message" value="Hello XML" />
<input type="submit" value="Echo as XML" />
</div></form>
</div>

</body>
</html>

xml-echo.jsp
------------
<%@page contentType="text/xml" pageEncoding="UTF-8"%>
<%

// !!! IMPORTANT !!! - the server must set the content type to XML
out.print("<root><message>" + request.getParameter("message") + "</message></root>");
%>