I have successfully set up a form that sends data to a MongoDB database. However, I am facing an issue with refreshing the input fields after the form is submitted without reloading the entire page.
After calling the resetBooks() function, it seems like it clears the form before posting the data. Is this the correct behavior?
How can I ensure that the form posts the data first and then clears the input fields afterwards?
<div class="booksInput">
<h4>Add a book</h4>
<form id="bookForm" method="post" action="/books"
target="hiddenFrame" onsubmit="resetBooks()">
<input class="form-control" name="title" type="text" placeholder="Enter book title">
<input class="form-control" name="author" type="text" placeholder="Enter author">
<input class="form-control" name="description" type="text" placeholder="Enter short description">
<button class="btn btn-primary" type="submit" value="Add Book">Submit</button>
</form>
</div>
<script>
function resetBooks(){
document.getElementById('bookForm').reset();
};
app.post("/", (req, res)=>{
let myBook = new Book (req.body);
myBook.save()
.then(item =>{
res.send("Book saved to database");
})
.catch(err=>{
res.status(err).send("unable to save to database");
});
});
</script>