i want to stay on the same page after i submit my form with Jquery and ajax to a servlet. Here's my code:
script.js
$(document).on('submit', '.myForm', function(e) {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(data) {
$('#antwort').html(data).fadeIn("slow");
//For testing
//alert(data)
}
});
e.preventDefault();
});
My kontakt.html code looks like this:
<form role="form" id="contactForm" method="POST" action="MailServlet" name="myForm">
<div class="form-group">
<label for="InputName">Ihr Name</label>
<input type="text" class="form-control" id="name" name="name">
</div>
<div class="form-group">
<label for="InputEmail1">Ihr EMail Adresse</label>
<input type="email" class="form-control" id="email" name="mail">
</div>
<div class="form-group">
<label for="InputMessage">Ihre Nachricht an uns</label>
<textarea class="form-control" id="nachricht" rows="8" name="nachricht"></textarea>
</div>
<button type="submit" class="btn btn-ar btn-primary" id="sendenBtn">senden</button>
<div class="clearfix"></div>
</form>
<div id="antwort" style="color:green; font-weight:bold;display:none;"></div>
And this is my servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
response.setHeader("Cache-control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
String name = request.getParameter("name");
String email = request.getParameter("email");
String nachricht = request.getParameter("nachricht");
out.println("Vielen Dank");
response.sendRedirect("kontakt.html");
}
So the problem is, that i got after submit the form a blank page with the text from the servlet. But i want that the response text from the servlet is showing in a div (antwort - right below the form) on the same page as my form