I have next JSP page that works on Google App Engine:
<%@ page contentType="text/html; charset=windows-1251" language="java" %>
<%@ page import="com.wedding.Register" %>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript">
function submitMyForm(button) {
var myForm = $(button).closest('form');
$.ajax({
url: $(myForm).attr('action'),
type: "post",
contentType:attr("enctype", "multipart/form-data"),
data: $(myForm).serialize(),
statusCode: {
400: function () {
$('.form-inline').after("<h1>400!</h1>");
},
200: function () {
$('.form-inline').after("<h1>200!</h1>");
}
}
});
}
</script>
</head>
<body>
<div class="container">
<%
String companyName = Register.getLoggedInCompanyName(request);
if (companyName == null) {
%>
<div class="navbar">
<div class="navbar-inner">
<a class="brand" href="#">Menu</a>
<ul class="nav">
<li><a href="/">Home</a></li>
<li class="active"><a href="/reg.jsp">Register</a></li>
</ul>
</div>
</div>
<div class="hero-unit">
<h1>Login</h1>
<p>Enter login credentials</p>
<p>
<form action="/reg?action=login" class="form-inline" method="post" enctype="multipart/form-data">
<input type="text" name="email" class="input-xlarge" placeholder="">
<input type="password" name="password" class="input-xlarge" placeholder="">
<button type="submit" class="btn" onClick="submitMyForm(this)">Login</button>
</form>
</p>
</div>
<%
} else {
%>
<div class="navbar">
<div class="navbar-inner">
<a class="brand" href="#">Menu</a>
<ul class="nav">
<li><a href="/">Home</a></li>
<li class="active"><a href="/reg?action=logout">Logout</a></li>
</ul>
</div>
</div>
<div class="hero-unit">
<h1>Error</h1>
<p>Error.</p>
</div>
<%
}
%>
</div>
<div id="footer">
<div class="container">
<p class="muted credit"></p>
</div>
</div>
</body>
The problem is that when a click button the form is sent to the server but if the server return 400 HTTP status code
$('.form-inline').after("<h1>400!</h1>");
is not invoked.
I’ve also tried success/error function and other HTTP codes but without success. The interesting thing is that it worked once and then always fails. Instead of adding new element to HTML the browser is redirected to the generated error page.
The status code is returned using
HttpServletResponse.sendError(400);
I’ve checked that a correct request and response are sent. I’ve also checked that the latest jquery is linked.
A
<button/>enclosed in a<form/>, by default, submits it. So, you need to stop the form submission.In the following example I will stick with jQuery instead of your mix of JavaScript and jQuery.
Since
$.ajaxis executed asynchronously, if you don’t stop the form submission the browser will still submit it hence redirecting the page.Feel free to test it out.