Blank Coder Blank Coder - 2 months ago 11
Ajax Question

Do post to servlet using jQuery

I am trying writing a server side validation using servlet and ajax, but it is not working properly. The value passed to the servlet cannot be accessed in the servlet.

How to fix this.

My javaScript function:

function employeeValidate() {
var params = {
firstName : document.getElementById("firstName").value
};
alert(params.firstName)// Prints value here
$.post("Employee.validate", $.param(params), function(response) {
alert(response); //success
});

return true;
}


Servlet Code

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("Hello");
System.out.println(request.getAttribute("firstName")); //printing null here
System.out.println("Hello");
}

Answer

Use request.getParameter() instead of request.getAttribute()