Hi every one, i have a project am working on and involves AJAX. I have a situation that i have to post forms without reloading a page. I have checked my jsp and com.oreilly.servlets package and is fine. I tried first with sending my post data without javascript i.e onSubmit event and it worked fine. Below are the two scripts
<%@ page import="java.sql.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.text.*"%>
<%@ page import="com.oreilly.servlet.*"%>
<%@ page import="com.oreilly.servlet.multipart.*"%>
<%
String filename = "";
String color = "";
try{
MultipartParser multPart = new MultipartParser(request, 10000024);
ByteArrayOutputStream baos =new ByteArrayOutputStream();
Part part = null;
while ((part = multPart.readNextPart()) != null) {
if(part.isParam()){
ParamPart paramPart = (ParamPart) part;
String paramName = part.getName();
String value = paramPart.getStringValue();
if(paramName.equals("color")){
color = value;
}
}else if (part.isFile()) {
FilePart filePart = (FilePart) part;
filename = filePart.getFileName();
if (!filename.equals("")) {
filePart.writeTo(baos);
}
}//end of isParam
}
out.print("Color = "+color);
out.print("Filename = "+filename);
}catch(Exception sqle){
out.print(sqle.getMessage());
}
%>
and the html file which has the javascript is as follows
<html>
<head>
<title>Remote Scripting Example</title>
<script type="text/javascript">
var xmlHttp
if (!xmlHttp) {
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
xmlHttp=false
}
}
ar URLto = "";
// function to build POST requests
function buildPOST(textForm) {
theForm = textForm;
var qs = ''
for (e=0;e<theForm.elements.length;e++) {
if (theForm.elements[e].name!='') {
var name = theForm.elements[e].name;
qs+=(qs=='')?'':'&'
qs+= name+'='+escape(theForm.elements[e].value);
}
}
qs+="\n";
return qs
}
// function to communicate with remote script
function send_post(theForm) {
var xmlMessage = buildPOST(theForm);
var URLto = theForm.action;
xmlHttp.open("POST", URLto, false);
alert(xmlMessage);
// for ie compatability
xmlHttp.setRequestHeader('Content-Type','multipart/form-data') ;
xmlHttp.send(xmlMessage) ;
}
function display_response() {
var optionDiv = document.getElementById("responseContainer");
optionDiv.innerHTML = xmlHttp.responseText;
}
</script>
</head>
<body>
<%
String color = "";
if(request.getParameter("color") != null){
color = request.getParameter("color");
}
%>
<!-- note: form must be named! -->
<form action="receive_upload.jsp" method="post" enctype="multipart/form-data" name="form1" onSubmit="send_post(this); display_response(); return false;">
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<tr>
<td>What is your favorite color? </td>
<td><input type="text" name="color"></td>
</tr>
<tr>
<td>File</td>
<td><input type="file" name="file"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td><input name="submit" type="submit" value="go >>"></td>
</tr>
</table>
<p> </p>
</form>
<div id="responseContainer">
</div>
</body>
</html>