Reputation: 1082
I have a form like the following.
<form class="comment-post" method="POST" action="/api/v1/comment/<%= post._id %>" enctype="multipart/form-data>
<div class="comment-section">
<textarea rows="4" name="comment"></textarea>
<button type="submit" class="button">Submit</button>
</div>
</form>
There can be more than one form with class 'comment -post'. I would like to add event listener on form submit so that the request is ajax like, as in the following.
const commentPostForms = document.querySelectorAll('.comment-post')
commentPostForms.forEach(form => {
form.addEventListener('submit', function(e) {
e.preventDefault()
axios
.post(this.action)
.then(res=>{
console.log(res)
})
.catch(console.error);
})
})
My question is how do I submit the form data along with my axios request. Currently, no form data is being sent.
I tried the following (edited),
function(e) {
e.preventDefault()
const formData = new FormData(e.target)
axios
.post(e.target.action, formData)
.then(res=>{
console.log(res)
})
.catch(console.error);
})
On the node js express server side I am doing console of the received object to see if the data has been actually passed.
router.post('/comment/:post_id/', comment );
const comment = (req, res) => {
console.log(req.body)
res.json(req.body);
}
I do not see 'comment' on req.body console.log
Upvotes: 1
Views: 1962
Reputation: 536
You need to generate the form data using the target of the event. So you should do:
const commentPostForms = document.querySelectorAll('.comment-post')
commentPostForms.forEach(form => {
form.addEventListener('submit', (e) => {
e.preventDefault()
const formData = new FormData(e.target);
axios
.post(e.target.action, formData)
.then(res=>{
console.log(res)
})
.catch(console.error);
})
})
Also, in your html set the enctype to form data. So you will have:
<form class="comment-post" enctype="multipart/formdata" action="/api/v1/comment/<%= post._id %>">
<div class="comment-section">
<textarea rows="4" name="comment"></textarea>
<button type="submit" class="button">Submit</button>
</div>
</form>
If you want to check if they key/pair your form data is really there. You can do after generating the form data:
for (let pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
Upvotes: 1