Hello @kartik,
Yes, JavaScript is involved. There are two parts: Hooking up a handler for the click events on the voting "buttons", and sending data to the server.
Here's a complete example code:
HTML:
<div class="article" data-itemid="427">
<a href="voteup" class="vote up" >Up</a>
<a href="votedown" class="vote down">Down</a>
<!-- ...the contents of the item... -->
</div>
JavaScript:
document.addEventListener("click", function(event) {
// Regardless of the below, we handle the event, so "consume" it
event.stopPropagation();
event.preventDefault();
// Get the anchor element
var voteLink = event.target.closest("a.vote");
if (!voteLink) {
// Didn't find one, bail
return;
}
// See if the vote has already been done or is in progress
if (voteLink.classList.contains("done") || voteLink.classList.contains("inprogress")) {
// Ignore the click, possibly tell the user why
return;
}
// Get the vote type
var voteType = voteLink.classList.contains("up") ? "up" : "down";
// Get the item we"re voting on
var item = voteLink.closest(".article");
// Get its ID
var itemId = item.getAttribute("data-itemid");
// If we didn"t get an ID...
if (!itemId) {
// ...report error
return;
}
// Mark "in progress" and initiate the vote; action continues
// in our callbacks below
voteLink.classList.add("inprogress");
var body = new FormData();
body.append("itemId", itemId);
body.append("voteType", voteType);
fetch("savevote", {
method: "POST",
body: body
})
.then(function(res) {
if (!res.ok) {
throw new Error("HTTP error " + res.status);
}
return res.text(); // or `res.json()` if you return JSON
})
.then(function(data) {
if (data === "ok") { // Or whatever
voteLink.classList.add("done");
} else {
// Report an error to the user, the server couldn"t record the vote
}
})
.catch(function(error) {
// Ajax failed, handle/report problem
})
.finally(function() {
// Not in progress anymore
voteLink.classList.remove("inprogress");
});
});
Hope it helps!!