1

I am trying to submit my form values using XMLHttpRequest.

HTML:

<form id="form" method="post" action="../myapi/submitRequest">
    <input type="text" name="type" placeholder="Type">
    <input type="text" name="eventDate" placeholder="Date">
    <input type="text" name="amount" placeholder="Amount">
    <input type="file" name="reciept">
    <input type="submit">
</form>

Somewhere in Java:

System.out.println(request.getParameter("type"));
System.out.println(request.getParameter("eventDate"));
System.out.println(request.getParameter("amount"));
System.out.println(request.getParameter("reciept"));

This prints the form fields value. Works perfectly!

But,

HTML:

<form id="form">
    <input type="text" name="type" placeholder="Type">
    <input type="text" name="eventDate" placeholder="Date">
    <input type="text" name="amount" placeholder="Amount">
    <input type="file" name="reciept">
    <input type="submit">
</form>

JavaScript:

const form = document.getElementById("form");

form.addEventListener('submit',function(event){

    let xhr = new XMLHttpRequest();
    xhr.open("POST","../myapi/submitRequest",true);

    let fd = new FormData(form);

    xhr.send(fd);

});

Somewhere in Java:

System.out.println(request.getParameter("type"));
System.out.println(request.getParameter("eventDate"));
System.out.println(request.getParameter("amount"));
System.out.println(request.getParameter("reciept"));

When I do this, I get null for all parameter values.

Am I doing something wrong?

Nbody
  • 1,168
  • 7
  • 33
double
  • 21
  • 5

1 Answers1

1

I think I found out why it was acting this way. When I was submitting the form data using the action attribute, I did not set the enctype attribute. So, when I was submitting the form, the content type was application/x-www-form-urlencoded. And when I was sending it using javascript, the content type was set to multipart/form-data; boundary=----WebKitFormBoundaryfxmNAuz7ZhhuUcZn.

I looked around and found out that request.getParameter() will return null if the content-type is not application/x-www-form-urlencoded. So, that was why I was getting those null values!

Helpful Posts

Convenient way to parse incoming multipart/form-data parameters in a Servlet

double
  • 21
  • 5