0

I created InformationServlet that whenever I need some details I can send it what I want (with AJAX) and it will return me the information.

I searched how to do it on Ajax and according to: How to send parameter to a servlet using Ajax Call

I used: url: "InformationServlet?param=numberOfPlayers"

But on the servlet the request's attributes doesn't contain the parameter I sent so I suppose I am not doing it correctly:
enter image description here

you can see that the attributes size is zero

Servlet:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            Gson gson = new Gson();
            Engine engine = (Engine)getServletContext().getAttribute("engine");
            String responseJson = "";

            if(request.getAttribute("numberOfPlayers") != null)
            {
                String numberOfPlayers = "";
                numberOfPlayers = gson.toJson(String.valueOf(engine.GetNumOfPlayers()));
                responseJson = numberOfPlayers;
            }

            out.print(responseJson);

        } finally {
            out.close();
        }
    }

JavaScript (AJAX request):

function getNumberOfPlayersAndPrintSoldiers()
{
      $.ajax({
        url: "InformationServlet?param=numberOfPlayers",
        timeout: 2000,

        error: function() {
            console.log("Failed to send ajax");
        },
        success: function(numberOfPlayers) {
            var r = numberOfPlayers;

        }
    });
}

1 Answer 1

1

Edit:

you probably want to use getParameter and not getAttribute

Moreover, please pay attention to the order of parameter name and his value:

request.getParameter("param");

instad of:

request.getParameter("numberOfPlayers");

because the url form contains parameter name first and then the parameter value. for example:

myurl.html?param=17

and if more parameters needed then use the separator & sign

myurl.html?firstName=bob&age=5
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.