Reputation: 51
I am having a problem with using ajax. If i remove the form tags then it works fine, the results show up on the same page. But with the form tags the results show on a different page i.e. straight to the servlet However i am trying to build this project with the form tags intact and to submit it from ajax instead of the form action, here is my code
account_recovery.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="js/jquery-1.11.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#subm").click(function(){
var email = $('#inputEmail').val();
if(email.length >= 3){
$(".statusMessage").html("<img src='images/loading.gif'><font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "ForgotPasswordServlet",
data: "email="+ email,
success: function(msg){
$(".statusMessage").html(msg);
}
});
}
else{
$(".statusMessage").html("<font color=red>Email should be <b>3</b> character long.</font>");
}
});
});
</script>
</head>
<body>
<jsp:include page="header.jsp"/>
<br/>
<div class="container">
<div class="col-md-6">
<form class="form-horizontal" action ="ForgotPasswordServlet" method ="POST">
<h4 class="form-signin-header" style="margin-top: 75px;">Forgot your password?</h4>
<br/>Enter the email address that you usually sign in with and we'll help you recover your account.
<label for="inputUser" class="sr-only"><b>Email:</b></label>
<br/><input type="text" id="inputEmail" name="email" class="form-control" placeholder="Enter your email address" required autofocus>
<span class="statusMessage"></span>
<br/>
<button class="btn btn-md btn-primary btn-success" type="submit" id="subm"/>Submit</button>
<br/>For more help to find your email address or password, visit the <a href="#">Help page</a>
</form>
</div>
</div><!---end container--->
<jsp:include page="footer.jsp"/>
</body>
</html>
Code to the servlet can be provided if needed
Upvotes: 0
Views: 2096
Reputation: 5041
You are not preventing the form submit. Instead try this.
<script type="text/javascript">
$(document).ready(function(){
$('form').on('submit',function(event){
event.preventDefault();
var email = $('#inputEmail').val();
if(email.length >= 3){
$(".statusMessage").html("<img src='images/loading.gif'><font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "ForgotPasswordServlet",
data: "email="+ email,
success: function(msg){
$(".statusMessage").html(msg);
}
});
}
else{
$(".statusMessage").html("<font color=red>Email should be <b>3</b> character long.</font>");
}
});
});
</script>
Upvotes: 1