Tuesday, 14 March 2017

Getting form name in a POST request Express JS (using EJS)

So I'm new to Node and Express and I am trying to build a simple voting app. What I would like to do is get the answer (either answer1 or answer2) and then update my database to increment the "answer1(2)_votes" by one.

However, before I can think about implementing this I need to be able to identify which question the user is answering.

At the moment I access the questions collection, render the index.ejs and send the result object in the render function, I then loop with ejs to display the questions and options from the database:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Voting App</title>
</head>
<body>

<% for(var i = 0; i < result.length; i++) { %>
  <form action="/submit-answer"  method="POST" id=<%= result[i].question %>>
    <div id="question"><%= result[i].question %></div>
    <input type="checkbox" name="answer1">
    <label for="answer1"><%= result[i].answer1 %></label>
    <input type="checkbox" name="answer2">
    <label for="answer2"><%= result[i].answer2 %></label>
    <button type="submit">Submit</button>
  </form>

<%}%>

</form>
</body>
</html>

I then get the data from the form like so (using body-parser)

app.post("/submit-answer", (req, res) => {
    console.log(req.body);
    res.redirect("/");
})

The only issue is this will return only the checkbox data (answer1: on or answer2: on). I need the "result[i].question" data as well (or any way of identifying the question) so I can find which question the form is responding to increment the amount of votes for the question.

How would I go about doing this? Am I approaching this completely wrong?



via swhizzle

No comments:

Post a Comment