I'm trying to make a simple ajax request using Java (JSP + Servlet) and Ajax (jQuery). The Ajax request is working as expected, and the servlet code is reached.
The problem is that I can't get the values of the parameters sent by the request. I get null values.
This is the code in the servlet:
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
String perfilId = request.getParameter("perfilId"); //Null value
String perfilNombre = request.getParameter("perfilNombre"); //Null value
try (PrintWriter out = response.getWriter()) {
Gson gson = new Gson();
JsonObject obj = new JsonObject();
obj.addProperty("mensaje", "Algún mensaje. Id: " + perfilId + ", Nombre: " + perfilNombre);
out.print(gson.toJson(obj));
out.flush();
}
}
Ajax request inside a JSP:
$.ajax({
type: "POST",
url: 'srvl_def',
cache: false,
contentType: "application/json;",
dataType: "json",
data: {
perfilId: $('#perfilId').val(),
perfilNombre: $('#perfilNombre').val()
},
success: function (data) {
alert(data.mensaje);
}
});
The request data looks like this:
perfilId=1&perfilNombre=nuevo
Perhaps I'm missing something?
EDIT
This is the HTML
<input type="text" id="perfilId" />
<input type="text" id="perfilNombre" />
<button type="button" id="btnGuardar">Enviar</button>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$('#btnGuardar').click(function (){
//ajax call
});
</script>