1
votes

I am having troulbe getting the path parameter out to a servlets doput method via and ajax function on a jsp page.

My jsp page with ajax:

    <form id="user-form">
    <table>
        <tr>
            <td> User id:</td>
            <td><input type="text" name="name" id="name"/></td>
        </tr>

    </table>
    <input type="submit" value="Submit"/>
</form>



<script>

var form = $('#user-form');

form.submit(function()
{
    $.ajax({
        url: 'TestServlet',
        data: form.serialize(),
        type: 'put',
        success: function(data){ 
            console.log(data);
        }
            });   
       });

Here is the part of the servlet method that is giving me trouble I haven't put the entire code in to save on clarity.

protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //System.out.println(request);
    System.out.println(request.getParameter("name"));
    String resourceBaseURL = "http://localhost:8080/TEST/webapi/orders/";
    String requestedOrder = request.getParameter("name");
    URL url;        
    HttpURLConnection con;
    String resultInXml = "";

    System.out.println("DoPut Called");
    // try to create a connection and request XML format
    try {

        ObjectFactory objFactory = new ObjectFactory();

        Car car = objFactory.createCar();
        car.setName(requestedOrder);
        url = new URL(resourceBaseURL + requestedOrder);
        con = (HttpURLConnection) url.openConnection();
        System.out.println(url);

When I submit some data through the form my System.out is confirming that the doput method is being called but the request.getParameter("name") is printing out to null.

Below is a copy of my console print out:

null
DoPut Called
http://localhost:8080/TEST/webapi/orders/null
Put

Null is the value for the form input but should be the name i type in.

I have get and post methods working fine as they are sent to the servelt in the regular way within the form action and method attributes.

Put and delete as far as i know can only be done through ajax or JQuery i just cant seem to figure it out.

I have tested the method out on postman and it is working perfectly.

I am really stuck on this and any help would be greatly appreciated.

1

1 Answers

0
votes

I'm wondering whether your form is actually loaded in DOM at the time you declare the "form" variable. Try wrapping your jquery code in DOM ready to ensure all elements of the page are ready:

$(document).ready(function() {

  var $form = $('#user-form');

  $form.submit(function(event) {

    event.preventDefault();

    var data = $form.serialize();
    console.log(data);

    $.ajax({
      ...
    });

  });
}