'Display data after POST request without reloading page

I have this node.js app where you can post comments on teachers profiles.

teacher.ejs

<!-- Form -->
<div class="">
      <form id="commentsForm" action="/teachers/<%=teacher[0].name%>" method="POST">
        <textarea class="comments" placeholder="Write here..." name="comm" id="comment" required></textarea>
        <button class="commentsButton" type="submit">Send comment</button>
      </form>
</div>

<!-- Displaying comments from database with GET request -->
<div id="commentsDiv" class="commentsDB">

  <% for(var i=0;i<comment.length;i++) { %>

    <div>
      <h5><%=comment[i].content%></h5>
          ...
    </div>

  <% } %>

</div>

index.js

// GET request (works fine)
router.get('/teachers/:name', function(req, res){

    db.query("SELECT * FROM comments", function(err, result){
        //...
        res.render('teacher', {comments: result});
    });    
});

// POST request
router.post('/teachers/:name', (req, res) => {

  const {comm} = req.body;

  db.query("INSERT INTO comments (comment) VALUES (?)", [comm], function(err, post){    
    // Insert correctly on DB        
  });    
});

The data typed on the textarea is inserted on the database but my webpage tries to reload and stays loading forever.

What I want is to show the new data inserted without reloading the page, how can I do that?

I tried inserting the new data directly with a script on teacher.ejs but it didn't work:

<!-- removing: action="/teachers/<%=teacher[0].name%>" method="POST" from <form>
and adding: onClick="addComment() on <button>-->
 <form id="commentsForm" >
    <textarea class="comments" placeholder="Write here..." name="comm" id="comment" required></textarea>
    <button class="commentsButton" type="submit" onClick="addComment()">Send comment</button>
 </form>

<script>
    function addComment(){

      var input = $('#comment').val();

      var newComment = document.createElement("h5");

      var textComment = document.createTextNode(input);

      newComment.appendChild(textComment);
              
      document.getElementById().appendChild(newComment);
  }
</script>

What is the best way to do this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source