E235
E235

Reputation: 13500

How to pass multiple parameters with JSON on Servlet to Ajax

I have JavaScript code that should get two parameters from servlet:
player name and player type (Human \ Computer)

The JavaScript use Ajax to send the request to the servlet named: UpdateStatusPaneServlet.java

On the servlet I created ArrayList<String> of 2 parameters and sent it to the Ajax.

You can see in the picture that the array appears ok.

I am not sure how to get the parameters using the indexOf() function or maybe I need to use other function.
I also tried with get() but it didn't work.
Also with playerNameAndType[0] it just print '['

enter image description here

JavaScript:

function printStatusPane() {

    $.ajax({
        url: "UpdateStatusPaneServlet",
        timeout: 2000,
        error: function() {
            console.log("Failed to send ajax");
        },
        success: function(playerNameAndType) {
            console.log("GOT ajax: " + playerNameAndType);
            $("#currentPlayer").append(playerNameAndType.indexOf(0));
            $("#playerType").append(playerNameAndType.indexOf(1));
        }
    });
}

Servlet (Java):

  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();
            String currentPlayerNameJSON = "";
            String playerTypeJSON = "";
            Engine engine = (Engine)getServletContext().getAttribute("engine");
            ArrayList<String> JSONRequest = new ArrayList<String>(2);

            currentPlayerNameJSON = gson.toJson(engine.GetCurrentPlayer().GetPlayerName());
            playerTypeJSON = gson.toJson(engine.GetCurrentPlayer().GetPlayerType().toString());

            JSONRequest.add(currentPlayerNameJSON);
            JSONRequest.add(playerTypeJSON);
            out.print(JSONRequest);

        } finally {
            out.close();
        }
    }

Upvotes: 1

Views: 3081

Answers (6)

Not a bug
Not a bug

Reputation: 4314

As you said, console output is ["Bob", "Human"] You can access that directly by index :

$("#currentPlayer").append(playerNameAndType[0]);
$("#playerType").append(playerNameAndType[1]);

What indexof() return is index of element you passed in argument.

playerNameAndType.indexOf("Bob")

will give you 0, the index of "Bob".

Example :

var person = ["Bob", "Human"];
document.write("Hey, " + person[0] + "!! You are first in array.");

Upvotes: 0

E235
E235

Reputation: 13500

Following D.T. comment I fixed it:

  var arrayJson = JSON.parse(playerNameAndType); 
  $("#currentPlayer").append(arrayJson[0]);
  $("#playerType").append(arrayJson[1]);

And it prints it correctly.

Upvotes: 1

RahulB
RahulB

Reputation: 2110

You are returning an ArrayList-"JSONRequest" having Json objects from your servlet. Try converting your arraylist to Json by JSON.stringify(JSONRequest). You can then handle this Json in client side.

Upvotes: 0

Delon
Delon

Reputation: 741

Instead of the below code

ArrayList<String> JSONRequest = new ArrayList<String>(2);
currentPlayerNameJSON = gson.toJson(engine.GetCurrentPlayer().GetPlayerName());
playerTypeJSON = gson.toJson(engine.GetCurrentPlayer().GetPlayerType().toString());
JSONRequest.add(currentPlayerNameJSON);
JSONRequest.add(playerTypeJSON);
out.print(JSONRequest);

Please try

currentPlayerNameJSON = gson.toJson(engine.GetCurrentPlayer().GetPlayerName());
playerTypeJSON = gson.toJson(engine.GetCurrentPlayer().GetPlayerType().toString());
HashMap<String, String> responseMap = new HashMap<String,String>();
resposeMap.put("name",currentPlayerNameJSON );
resposeMap.put("type",playerTypeJSON );
out.print(responseMap.toString());

and in the javaScript you can

function printStatusPane() {

    $.ajax({
        url: "UpdateStatusPaneServlet",
        timeout: 2000,
        error: function() {
            console.log("Failed to send ajax");
        },
        success: function(playerNameAndType) {
           var json = $.parseJSON(playerNameAndType);    
            $("#currentPlayer").append(json['name']);
            $("#playerType").append(json['type']);
        }
    });
}

Upvotes: 0

Sudharsan S
Sudharsan S

Reputation: 15403

indexOf returns the position of the array value.Use key index to take the array value and append in to the id

playerNameAndType = ["Bob", "Human"];
$("#currentPlayer").append(playerNameAndType[0]);
$("#playerType").append(playerNameAndType[1]);

Upvotes: 0

collab-with-tushar-raj
collab-with-tushar-raj

Reputation: 1287

you are getting an array of objects . Just simply retrieve the object from it's index .

$("#currentPlayer").append(playerNameAndType[0]);
$("#playerType").append(playerNameAndType[1]);

Upvotes: 0

Related Questions