response data sent from servlet are not received on return of an Ajax form submit
Hello,
I coded a simple Servlet and jsp to learn jQuery Ajax Form submit facility. I used Netbeans to trace the execution of the code. I am sure that the Servlet does send out data as http response. However, the data are not received by the client js code. I don't know why. And, it is very strange that the alert() dialog pops up before the servlet sends out the data completely. Can anyone help me identify the errors?
*** my servlet code (see below) ***
...
public class handlerServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
java.util.Date now = new java.util.Date();
out.print("<p>testing at ");
out.print(now.toString());
out.println("</p>");
} finally {
out.close();
}
}
...
*** my JavaScript code in jsp (see below) ***
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page session="false" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>test</title>
<link type="text/css" href="<%=request.getContextPath()%>/js/jquery/css/smoothness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery/js/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery/js/jquery-ui-1.7.2.custom.min.js"></script>
<script type="text/javascript" >
<!--
$(document).ready(function() {
$('#myForm').submit(function() {
var data2submit = $('#myForm').serialize();
$.post("http://localhost:8084/js/hs", $('#myForm').serialize(), function(data) {
alert(data);
$('#divToUpdate').replaceWith(data);
});
});
})
// -->
</script>
</head>
<body>
<form id="myForm" method="post" >
Name: <input type="text" name="name" />
<input type="submit" value="Submit Comment" />
</form>
<p>Returned:</p>
<div id="divToUpdate" >abc</div>
</body>
</html>