I am posting a comment with Axios (without refreshing page) client side to server. the comment saves successfully and sends saved data as a response. I want that response data shown on a web page after saving. I am not understanding how to do that, support me. here is my code into
<script>
const form = document.querySelector('.formPost');
const pushComment = document.querySelector('#pushComments').innerHTML
const formEvent = form.addEventListener('submit', event => {
event.preventDefault();
const postId = document.querySelector('#postId').value;
const adminId = document.querySelector('#adminId').value;
const comment = document.querySelector('#comment').value;
const commentData = {postId, adminId,comment};
async function doComment(form){
await axios({
url:"/comment",
method:'post',
data:commentData,
}).then((responseData)=>{
var value = responseData.data
document.getElementById('pushComments').innerHTML = value
console.log(responseData.data)
})
}
doComment()
function nulldata(){
const comment = document.querySelector('#comment').value=''
}
nulldata()
});
here sever side data
route.post('/comment', async (req,res)=>{
const user = req.user
const comments = {
postId:req.body.postId,
admin: req.body.adminId,
comment:req.body.comment,
name:req.user.name,
email:req.user.username
}
console.log( comments)
const comment = await Comment.create(comments)
res.json({comment})
})
You're receiving a json response containing a comment-document from the server side.
Assuming you want to append the comment field from the response and pushComments is a simple <ul> you could simply do:
const {comment} = responseData.data;
const existingCommentsList = document.getElementById('pushComments').innerHTML;
document.getElementById('pushComments').innerHTML = `${existingCommentsList}<li>${comment.comment}</li>`;