Eutherpy
Eutherpy

Reputation: 4581

Servlet can't read XMLHttpRequest parameter

I am creating a HTTP POST request from JavaScript like this:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <input id="num" type="text" />
    <input type="button" id="btn" value="submit" onclick="func()"/>
    <script>
    function func() {
        var num = document.getElementById("num").value;
        var request = new XMLHttpRequest();
        request.open("POST", "/Servlet/MyServlet", true);
        request.onreadystatechange = function() {
            if(request.readyState == 4 && request.status == 200) {
                 ...        }
        };
        request.setRequestHeader("Content-Type", "application/www-x-form-urlencoded");
        request.send("num=" + num);
    }
    </script>
</body>
</html>

and this is my servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
              ...
            int num = Integer.parseInt(request.getParameter("num"));            
    }

The servlet is called, but the parameter is null.

Upvotes: 0

Views: 344

Answers (2)

hiren
hiren

Reputation: 1105

Found the issue: It is the setRequestHeader line. Yours is application/www-x-form-urlencoded which should be application/x-www-form-urlencoded. Try replacing the below line into your code. Otherwise your code works like charm (I have tried it).

 request.setRequestHeader("Content-type","application/x-www-form-urlencoded");

Upvotes: 2

Deniss B.
Deniss B.

Reputation: 281

Your code seems OK, try printing out all the parameters you get with request.getParameterMap(); What are you passing as a parameter in num variable? I am assuming it's a number but if it's a string you need to make sure it's URL encoded as well

Upvotes: 0

Related Questions