I am counting the views on a post on my website and for that I have created a 'more' button (but styled as a link) after some text so that the user clicks on that and the view count increases. The button submits a post request and I increment the view count in the database.
The problem is that I have 2 separate pages (which might increase in the future) that display the posts and they both have this 'more' button which submits the post request to the same route. I want the user to click the button and stay on that same page on that same location but in express we are required to res.redirect or render 1 page which isn't possible in this case. I tried to redirect to ('/'), but this goes only to one of the 2 pages that I talked about and not the current page. Moreover, when redirecting, the extra paras shown on clicking that button also vanishes, basically going to the original orientation. I am happy to change the entire logic of this function as long as you cannot find any solution with this one...
router.post("/clicked-more", ensureAuth, async (req, res) => {
try {
let secId = req.body.clicked_more
const sec = await XXX.find({
_id: secId
}).lean();
sec[0].views++
await XXX.findOneAndUpdate({
_id: secId
}, {
views: sec[0].views
});
res.redirect('/')
} catch (err) {
console.log(err);
// res.send(err)
res.render("../views/error/500");
}
});
This is one of my 2 pages (hbs-handlebars). (2nd one has the same function as this one)
<form action="/clicked-more" method="post">
<div class="wrapper">
<p class="startPara">{{stripTags (truncate body 200)}}<span class="dots">...</span></p>
<span class="content">
<p>{{stripTags (truncate body 400)}}</p>
</span>
<button type="submit" name="clicked_more" value={{_id}} class="link-button buttonReadMore"
onclick="readMoreFunction(this)">more</button>
</div>
</form>
This is my 'read more' function
function readMoreFunction(el) {
var parent = el.closest(".wrapper")
var dots = parent.querySelector(".dots");
var contentText = parent.querySelector(".content");
var btnText = parent.querySelector(".buttonReadMore");
var startPara = parent.querySelector(".startPara");
btnText.style.display = "none";
startPara.style.display = "none";
dots.style.display = "none";
contentText.style.display = "inline";
}