Good morning,
I have a simple form in which I submit via ajax, so my servlet takes that result and gives an answer, from the answer, the ajax will do something. I can see the response in the browser, but I do not get the result in ajax.
JSP:
'
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<script src="http://localhost:8080/lib/js/jquery-3_2_1_min_js.js"></script></head><body><formmethod="POST" ID="form1" >
<%-- <%= request.getAttribute( "answer" ) --%>
Name: <input type="text" name="name" /><br />
E-mail: <input type="text" name="email" /><br />
Address: <input type="text" name="address" /><br />
<input type="submit" value="record" />
</form>
<script>
$(document).ready(function(){
$("#form1").on("submit", function(e){
e.preventDefault();
console.log("tried to submit the form");
$.ajax({
url: "/QualidadeWeb/testando",
method: "POST",
//async: false,
data: $(this).serialize(),
succes: function(data){
console.log(data);
console.log("it worked");
},
error: function(data){
console.log(data);
console.log("didn't work");
}
});
});
});
</script>
</body>
</html>
'
Servlet:
'
package controllers;
import java.io.IOException;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class addContatoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException{
response.addHeader("Access-Control-Allow-Origin", "*");
RequestDispatcher rd;
rd = request.getRequestDispatcher("/WEB-INF/View/adiciona-contato.jsp");
System.out.println("testando GET 444");
try{
rd.forward(request, response);
}catch(Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.addHeader("Access-Control-Allow-Origin", "*");
System.out.println("Testando Post 1234");
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
out.write("the contact's name is: " + name);
}
}
'
How can you see the answer works
Butmyajaxdoesnotcatchtheresponseintheconsole.log,itlookslikeajaxgetslostmidway:
It only reaches the first console.log, does the post and then does nothing else, what could it be?
Thank you in advance!