0

I'm trying to submit form data from a html file using $.post method. But, in the server side, servlet is getting null. No field is empty and null. Can anyone tells me what is the issue? Thanks. BTW, I'm showing here just one field but actually I've several fields in the form. Here is my code:

html

        <form id="reservationsForm" name="reservationsForm" method="post" action="Reservations" 
            class="well form-horizontal" align="left" style="width:865px;border:2px solid #000000;margin:auto;"> 
        <br>
        <div >                              
        <div align="left" class="form-group">
          <label class="col-md-2 control-label" style="font-family:sans-serif;color:black"><B>Pickup Date:</B></label>  
          <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
          <input placeholder="Please select a date" class="form-control"  type="text" id="datepicker" style="width: 
        238px;">
          </div>
          </div>
        </div>                  
        <br> 
<td><label align="center" style="font-family:sans-serif;color:black"># of Stops</label></td>
<select class="form-control selectpicker" id="stops" name="stops" size="1" tabindex="14" width="150px">

        <option value="0">No Stop</option>

        <option value="1">1</option>

        <option value="2">2</option>

        <option value="3">3</option>
   </select>
    <div align="center">
            <input onclick="send()" type="submit" name="submit" value="Send" style="font-weight:600" class="btn btn-primary">
    </div>  
     </form>

JS

var send = function() {

         var pickUpDate = document.getElementById('datepicker').value;
         var totalStops = document.getElementById('stops').value;

         var inputData = {"pickUpDate":pickUpDate,
                           "totalStops":totalStops }
         $.post('http://localhost:8080/WelcomeLimoUsa/Reservations', inputData, myData, "json");

        function myData(data) {

            }
     };

servlet

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

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            if( request != null) {
        System.out.println("PickUp Date is: " + 
request.getParameter("pickUpDate"));
     System.out.println("total Stops is: " + request.getParameter("totalStops"));


     String pickUpDate = request.getParameter("pickUpDate");
     Integer totalStops = Integer.parseInt(request.getParameter("totalStops"));

            }else{
                System.out.println("#############Request is null#########");
            }
        }
        catch (Exception e){
            e.printStackTrace();
            System.out.println("Exception occured");
        }
    }

}

error in server side

java.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Integer.java:542)
    at java.lang.Integer.parseInt(Integer.java:615)
    at com.welcomelimo.controller.Reservations.doPost(Reservations.java:50)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2508)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2497)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
java.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Integer.java:542)
    at java.lang.Integer.parseInt(Integer.java:615)
    at com.welcomelimo.controller.Reservations.doPost(Reservations.java:50)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2508)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2497)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Exception occured
PickUp Date is: null
JoeZ
  • 79
  • 1
  • 2
  • 11
  • Your Exception does not match your code. There is no ``Integer.parseInt`` in the java servlet. And you're trying to access a GET or POST variable with the name "pickUpDate", but there is no such thing. You post a json structure, not key/value pairs. – f1sh Nov 30 '16 at 18:24
  • @ f1sh, I updated the post. Servlet is getting "pickUpDate" from query parameter I'm sending from front-end using $.post() where I included the "pickUpDate" in a JSON object. – JoeZ Nov 30 '16 at 18:41
  • then what is the problem if the value arrives at the servlet? – f1sh Nov 30 '16 at 18:45
  • @ f1sh, I'm not getting the value in the server end I'm supposed to get instead I'm getting null though I'm sending value. – JoeZ Nov 30 '16 at 18:48

1 Answers1

0

Try debugging on the client side. In the Javascript:

var totalStops = document.getElementById('stops').value;

// look if totalStops contains the expected value
console.log(totalStops);

var inputData = {"pickUpDate":pickUpDate,
                           "totalStops":totalStops }

EDIT1: after confirmed expected value.
Check all the servlet's request parameters by using:

Enumeration<String> names = request.getParameterNames();
        while(names.hasMoreElements()) {
            String name = names.nextElement();
            response.getWriter().append(name + "=" + request.getParameter(name) + "<br>");
        }

EDIT2: after seeing that the server don't receive the parameters.

As i suggested you can show all parameter you received in the servlet. I tryied this with your code and get: stops=2<br>submit=Send<br>

So the form was submitted, but without ajax.
The ajax code is not stopping the default submit event.

You remove the onclick="send()" and let the line be just:

 <input type="submit" name="submit" value="Send" style="font-weight:600" class="btn btn-primary">

You can bind the the form submitting with javascript in this way:

// when the html document is ready / parsed from browser
     $( document ).ready(function() {
         // Bind an event handler to the "submit" JavaScript event
         $("#reservationsForm").submit(send)
     });

To prevent the default submit event add return false; at the end of your send()-function in Javasript:

 var send = function(event) {

     var pickUpDate = document.getElementById('datepicker').value;
     var totalStops = document.getElementById('stops').value;

     var inputData = {"pickUpDate":pickUpDate,
                       "totalStops":totalStops }
     $.post('http://localhost:8080/jee6/FormTestServlet', inputData, myData, "json");

    function myData(data) {

        }

    // add return false to prevent the default sumbit
    return false;
};   

You can see in the documentation of jQuery.submit()

... we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler.

code_angel
  • 1,537
  • 1
  • 11
  • 21