Soshiribo Soshiribo - 1 month ago 5
Ajax Question

Using jQuery's Ajax to send string to HTTPServlet: Request is empty

I'm trying to send data back to my HTTPServlet on the press of a button.
At the end, my goal is to send back JSON data but for now, I'm just trying to send back a string.

When I click on the

saveThis
-button my server prints out "Empty" because my request data happens to be empty; What am I missing here?

My JavaScript:

$("#saveThis").click(function(e)
{
$.post("clientserver", {
"loadProds": 1,
"test": "Hello"
});
});


And my Servlet:

@WebServlet(urlPatterns= {"/clientserver"})
public class SayHelloServlet extends HttpServlet
{
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
if(request.getParameter("saveThis") != null)
{
String json = request.getParameter("test");
System.out.print(json);
} else
{
System.out.print("Empty");
}
}
}

Answer

You are making a POST request, so the data will be in the body of the request, not the parameters.

Try using:

request.getReader()

Or:

request.getInputStream()

To grab the request body in your Java code.

Comments