Reputation: 33
I am creating something like the reddit comment section, someone can comment something and people can reply to that comment.
I am using Node, Express, MySQL, EJS.
The problem: I don't know how to make the upvote/downvote part, I don't know how to make an onclick event which will tell my DB to upvote/downvote that comment by 1 without reloading the page.
Express code:
app.get("/posts", function(req,res){
connection.query(`SELECT post FROM testingposts`, function(error,result){
if(error){
console.log(`error 757`)
} else {
console.log(`works btw`)
res.render("posts", {result: result })
}
})
})
app.post("/posts", function(req,res){
let post = req.body.post;
console.log(`req.body`)
console.log(req.body.theValue)
connection.query(`INSERT INTO testingposts(post) VALUES(?)`, [req.body.post], function(error,result){
if(error){
console.log(`error 555`)
} else {
res.redirect("/posts")
}
})
})
EJS:
//This part basically creates the html elements for the comments.
//But I haven't added the upvote/downvote elements yet.
<% for(let i = 0; i < result.length; i++){ %>
<div value="<%= i %>">
<p><%= result[i].post %></p>
<input id="<%= i %>" type="submit" value="reply" onclick=bob(event) >
<input type="submit" value="report" >
</div>
<form method="post" action="posts" style="display:none">
<textarea name="replytextarea" id="" cols="30" rows="10"></textarea>
<input type="text" class="forValue" name="theValue" value="5" style="display: none">
<input type="submit" value="submit btw" onclick="setValue(event)">
</form>
<% } %>
I tried trying something with Fetch, but it didn't work properly for me.(I don't know what to write as the URL)
Upvotes: 0
Views: 3006
Reputation: 1055
Cool. So one of the neat things about express is that you can make whatever endpoints you want, that will do whatever you want. So let's say you want to make an AJAX request that upvotes a certain comment? You can create it.
(These are PUT
routes because they change information about a record that already exists.)
router.put('/posts/upvote/:comment_id', (req, res) => {
// something that increments the number of upvotes for that particular comment
res.status(200).json({voteNum: // new vote number})
})
router.put('/posts/downvote/:comment_id, (req, res) => {
// something that decrements the number of downvotes for that particular comment
res.status(200).json({voteNum: // new vote number})
})
And then you can use it:
// when the upvote button is clicked
fetch(`/posts/upvote/${your_comment_id}`, { method: 'PUT', credentials: 'include' })
.then(res => res.json())
.then(jsonRes => {
// get the element with the number of votes
element.innerText = jsonRes.voteNum
})
Of course, this will need some work to fit it into your code. But, overall, if you're ever not sure what to write for the URL... just remember, you can make it up.
Upvotes: 2