1

I would like to send data from the browser to backend using the Fetch API.

HTML:

<form action="#" id="comment-form">
   <div class="comment-enter-field">
         <textarea placeholder="Write a comment..." class="comment-input" name="comment-input"></textarea>
         <div class="comment-footer">
            <input type="submit" value="Comment" class="comment-submit">
         </div>
   </div>
</form>

JavaScript:

// Submitting the form
const commentData = new URLSearchParams();
const commentInput = document.querySelector('.comment-input');
const sessionData = JSON.parse(sessionStorage.getItem('userEntity'));
// Append all the data that we need
commentData.append('comment', commentInput.value);
commentData.append('data', sessionData);

document.getElementById('comment-form').addEventListener('submit', (e) => {
    e.preventDefault();
    console.log(commentInput.value); // This outputs the correct string that I would like to be shown in backend
    fetch('../comments', {
        method: 'POST',
        body: commentData
    })
});

Java:

@WebServlet("/comments")
public class Comments extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getParameter("comment"));
    }
}

I would simply like to get the value of commentInput.value but the weird thing is that System.out.println(req.getParameter("comment")); returns NOTHING. System.out.println("Hello world"); works but req.getParameter("comment") doesn't return anything, not even an error. What am I doing wrong?

Ray
  • 125
  • 3
  • 12
  • Have you tried using Postman to check that the Backend is working correctly and you're using the correct path? – GMaiolo Jun 30 '19 at 23:24
  • You need to provide the HTML that contains `comment-form` – Tibrogargan Jun 30 '19 at 23:25
  • @GMaiolo no, I didn't tried it with Postman but since `System.out.println("Hello world");` works when I submit the form, I guess the path must be fine. – Ray Jun 30 '19 at 23:33
  • @Tibrogargan I have updated my post. – Ray Jun 30 '19 at 23:34
  • 1
    Move all your `commentData` code into the submit event handler. Right now, you're only adding the initial form values (probably empty) when your page first loads – Phil Jul 01 '19 at 00:18
  • 1
    @Phil omg, you're absolutely right! I feel so stupid that I didn't realize that. Thank you so much, you helped me a lot! – Ray Jul 01 '19 at 00:25
  • I think you're trying to get the value the wrong way. You need to use something like getReader() or getInputStream(). See if this link helps you https://stackoverflow.com/questions/14525982/getting-request-payload-from-post-request-in-java-servlet – Paulo Vagner Jul 01 '19 at 00:00

0 Answers0