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?