I'm generating a little form consisting of a single button using javascript and when the form submits the backend isn't getting any data.
Code to generate the form:
let form = document.createElement("form");
form.action = "<%=application.getContextPath() + "/MyAds"%>";
form.method = "POST";
let buttonPublish = document.createElement("button");
buttonPublish.setAttribute("name", "status");
buttonPublish.setAttribute("type", "submit");
buttonPublish.setAttribute("value", "publish-" + post.id);
buttonPublish.classList.add("btn", "btn-primary", "btn-primary", "btn-fixed-size-100");
buttonPublish.innerText = "Publish";
form.appendChild(buttonPublish);
div.appendChild(form);
Resulting HTML:
<form action="/p3/MyAds" method="POST">
<button name="status" type="submit" value="publish-13" class="btn btn-primary btn-fixed-size-100">Publish</button>
</form>
Backend (Java Servlet):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getAttribute("status")); //<-- Prints null
if (request.getAttribute("status") != null) {
// Not implemented yet
}
else {
// ...
}
}
I also tried adding a text input to the form and I wasn't receiving that value either so I think the problem isn't the button itself but something related to the form.
EDIT: As @epascarello pointed out in a comment I was using the wrong function. Replacing getAttribute with getParameter fixed it.