1

I am trying to fill a table using a POST command to my servlet, but instead of sending a POST request, my webpage sends a GET request to the servlet. Here is my

$(document).ready(function() {
  $.get("league", function(responseJson) {
    if (responseJson != null) {
      $("#tableleague").find("tr:gt(0)").remove();
      var table1 = $("#tableleague");
      $.each(responseJson, function(key, value) {
        var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
        rowNew.children().eq(0).text(value['teams']);
        rowNew.children().eq(1).text(value['playedgames']);
        rowNew.children().eq(2).text(value['wongames']);
        rowNew.children().eq(3).text(value['tiegames']);
        rowNew.children().eq(4).text(value['lostgames']);
        rowNew.children().eq(5).text(value['scoredgoal']);
        rowNew.children().eq(6).text(value['scoredgoal']);
        rowNew.children().eq(7).text(value['scoredgoal']);
        rowNew.appendTo(table1);
      });
    }
  });
});

function addData() {
  var t1 = $("#firstteam").val();
  var t2 = $("#secondteam").val();
  var s1 = $("#score1").val();
  var s2 = $("#score2").val();
  $("#firstteam").val('');
  $("#secondteam").val('');
  $("#score1").val('');
  $("#score2").val('');
  var data = {
    firstteam: "t1",
    secondteam: "t2",
    score1: "s1",
    score2: "s2"
  }

  $.ajax({
    type: "POST",
    url: "league",
    data: JSON.stringify(data),
    contentType: "application/x-www-form-urlencoded",
    dataType:'json',
    success: function(data, textStatus, jqXHR) {
      if (data.success) {
        $("#error").html("<div><b>Success!</b></div>" + data);
      } else {
        $("#error").html("<div><b>Information is Invalid!</b></div>" + data);
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log("Something really bad happened " + textStatus);
      $("#error").html(jqXHR.responseText);
    }
  });
}
<h1>League Table</h1>
<table cellspacing="0" id="tableleague" style="width:100%">
  <tr>
    <th scope="col">Teams</th>
    <th scope="col">Won</th>
    <th scope="col">Tie</th>
    <th scope="col">Lost</th>
    <th scope="col">Scored</th>
    <th scope="col">Received</th>
    <th scope="col">Points</th>
  </tr>
</table>

<form method="POST">
  <div class="form_group">
    <label for="FirstTeam">FirstTeam:</label>
    <input type="text" class="form_control" id="firstteam">
  </div>
  <div class="form_group">
    <label for="Score1">Score1:</label>
    <input type="text" class="form_control" id="score1">
  </div>
  <div class="form_group">
    <label for="Score2">Score2:</label>
    <input type="text" class="form_control" id="score2">
  </div>
  <div class="form_group">
    <label for="SecondTeam">SecondTeam:</label>
    <input type="text" class="form_control" id="secondteam">
  </div>
  <div class="form_group">
    <button type="submit" class="addbutton" id="addbut" onclick="addData();">Add match</button>
  </div>
</form>

<div id="error"></div>

Here is what I see in my debugger immediately after I press the Add match button:

enter image description here

The error I receive in the console is this one:

POST http://localhost:8080/league/league 500 (Internal Server Error)

What am I doing wrong with my code? I tried many solutions but nothing worked.

My servlet code:

@WebServlet("/league/*")
public class PopulateTable extends HttpServlet {
private static final long serialVersionUID = 1L;

public PopulateTable()
{

}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    try
    {
        ArrayList<League> league = new ArrayList<League>();
        league= Controller.getAllController();
        Gson gson = new Gson();
        JsonElement element = gson.toJsonTree(league, new TypeToken<List<League>>() {}.getType());

        JsonArray jsonArray = element.getAsJsonArray();
        response.setContentType("application/json");
        response.getWriter().print(jsonArray);
    }
    catch (SQLException ex)
    {
        ex.printStackTrace();
    }
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    try {
        PrintWriter out = response.getWriter();
        JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);

        int s1 = Integer.parseInt(data.get("score1").getAsString());
        int s2 = Integer.parseInt(data.get("score2").getAsString());

        String t1 = data.get("firstteam").getAsString();;
        String t2 = data.get("secondteam").getAsString();;
        int ok = Controller.update(t1, t2, s1, s2);
        JsonObject myObj = new JsonObject();

        if(ok ==  1)
        {
            myObj.addProperty("success", true);
        }
        else {
            myObj.addProperty("success", false);
        }
        out.println(myObj.toString());

        out.close();

    }
    catch (SQLException ex)
    {
        ex.printStackTrace();
    }
}

}
Artyomska
  • 1,309
  • 5
  • 26
  • 53
  • 1
    `instead of sending a POST request, my webpage sends a GET request` You're using `$.get()`...? – Rory McCrossan Jun 05 '17 at 08:38
  • Did you check your server error logs? `500 Internal Server Error` indicates something wrong at your JSP end, probably not able to save/insert the data. You need to check logs. – Milan Chheda Jun 05 '17 at 08:43
  • I am using .get as my first function,to fill the table when I am first loading the page, but when I press the Add match button my page should send an AJAX POST request, which it doesn't do. – Artyomska Jun 05 '17 at 08:45
  • 1
    change button type – Gurkan Yesilyurt Jun 05 '17 at 09:16
  • Changed the button type and I see a whole new world to say it like that. Looks like my error is in servlet, the int s1 variable giving me a java.lang.NumberFormatException. – Artyomska Jun 05 '17 at 09:20
  • before, check your variables whether null or not and trim() all strings, later convert it. – Gurkan Yesilyurt Jun 05 '17 at 09:26

2 Answers2

1

Well, have done below changes to your addData() function. Inside$.ajax() function, create a param object to hold the form data and it can be passed to servlet like this.

var param = 'formdata='+JSON.stringify(data);
$.ajax({
    type: "POST",
    url: "/league",
    data: param,
    dataType:'json',
    success: function(data, textStatus, jqXHR) {
      if (data.success) {
        $("#error").html("<div><b>Success!</b></div>" + data);
      } else {
        $("#error").html("<div><b>Information is Invalid!</b></div>" + data);
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log("Something really bad happened " + textStatus);
      $("#error").html(jqXHR.responseText);
    }
  });

You can access this data object in your PopulateTable servlet with HttpServletRequest object. You can access like

String formData = request.getParameter("formdata");

The above formData holds form input values in json format and it is good for parsing.

Hope this helps!!!

harshavmb
  • 3,404
  • 3
  • 21
  • 55
  • How can I parse the string to get the score1,score2,teamfirst and teamsecond from it? I am new to servlet so sorry if my question seems stupid. – Artyomska Jun 05 '17 at 09:37
  • Same, you need to use gson/jackson or some json parsing library. Just to be sure about my code. Can you print a sysout statement inside `doPost` method of `PopulateTable` servlet? It would be `System.out.println(request.getParameter("formdata"));` – harshavmb Jun 05 '17 at 09:41
  • I put a println in my code, but I can't see the result anywhere, not in the Tomcat console or in the Chrome console. – Artyomska Jun 05 '17 at 09:44
  • It should be printed on Tomcat console as the print is a java sysout is java method. Has the 500 stopped? – harshavmb Jun 05 '17 at 09:45
  • Yes it has fortunately. All I have to do is to figure out how do I split the string to get score1,score2 and the rest in separate variables. Still nothing is printed in the tomcat console though. – Artyomska Jun 05 '17 at 09:46
  • Exactly. Since the 500 has stopped and you should see a POST request in browser network console. If these two have been resolved, I would request you to raise a new question on SO to parse the passed json as it's not in this question scope. Hope this helps! – harshavmb Jun 05 '17 at 09:49
  • You are right. The initial problem was fixed. Thank you :D – Artyomska Jun 05 '17 at 09:50
  • No problem.. Cheers.. – harshavmb Jun 05 '17 at 09:51
0

It is because of content-type, when you are sending data by using post method you have to use x-www-form-urlencoded (which is default in $.ajax) like,

contentType: "application/x-www-form-urlencoded"

and not

contentType: "application/json",

also use dataType:'json' to get JSON response. Read more about contentType and dataType on $.ajax()

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
  • So should I make another class in my servlet? For now I have a single class which is mapped to league with a doGet method and a doPost method. – Artyomska Jun 05 '17 at 08:46
  • I receive the same error. I changed my Ajax from league to leagues, I made a new class in my servlet mapped to leagues, with only a doPost method, but nothing was fixed. – Artyomska Jun 05 '17 at 08:55
  • Try once by using the `url:'/league'` in $.ajax instead of `url:'league'`. – Rohan Kumar Jun 05 '17 at 08:57