I am currently developing a back-end API that is connected to a front-end interface in order to create a simulation of a worm moving up and down in a hole (just a test). However, I am facing difficulties in making a POST request to the API from a form while utilizing Bootstrap.
Here is my form:
<div>
<h2>Insert data for movement</h2>
<form method="POST" action="localhost:3000/move/data" role="form" id="dataForm">
<div class="form-group">
<label for="holeSize">Length:</label>
<input type="number" class="form-control" id="holeSize" value="20"/>
</div>
<div>
<label for="moveForward">Forward:</label>
<input type="number" class="form-control" id="moveForward" value="5"/>
</div>
<div>
<label for="moveBackward">Backward:</label>
<input type="number" class="form-control" id="moveBackward" value="3"/>
</div>
</form>
<button type="submit" class="btn btn-primary" onclick="sendData()">Start</button>
<button type="reset" class="btn btn-primary" onclick="reset()">Reset</button>
</div>
Additionally, here is my move.js file:
const form = document.getElementById("dataForm");
form.addEventListener("submit", function (event) {
event.preventDefault();
sendData();
})
function sendData() {
console.log('start')
document.getElementById('worm').style.top = "300px";
const XHR = new XMLHttpRequest();
const FD = new FormData(form);
XHR.addEventListener("load", function (event) {
alert(event.target.responseText);
});
XHR.addEventListener("error", function (event) {
alert('Oops! Something went wrong');
});
XHR.open("POST", "http://localhost:3000/move/data");
XHR.send(FD);
}
I added the line "document.getElementById('worm').style.top = "300px";" to test if the button click is functioning properly. The DIV does move on the screen (transition is working), but no POST request is being sent.
Update -> Following a suggestion, I placed the move.js script at the end of my HTML file, and then it started to work as intended.
However, the form data is not being retained. I included the following code:
let movement = req.body;
console.log(movement);
but it simply returns an empty object {}