Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!