Reputation: 567
I am working on a multiple-choice question app and I am a database where I am storing the users answers. I just want to store the first answer they select to store it in the database. After the first selection, they can still click on the other answers to run the checkAnswer()
but the storeAnwserStats()
should not run. How can I do that?
app.js
function storeAnwserStats(questionId, answerId){
$.ajax({
url : "/store_stats",
type : "POST",
data : JSON.stringify({
question_id: questionId,
answer_id:answerId,
}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
})
.done(function(data){
console.log("After " +data["correct_answer"]);
});
}
function checkAnswer(divSelected, answerId, questionId, isCorrect){
if(isCorrect == 1){
divSelected.style.backgroundColor = "green";
}
else{
divSelected.style.backgroundColor = "red";
}
storeAnwserStats(questionId, answerId)
}
[1]: https://i.sstatic.net/xyZfY.png
Upvotes: 0
Views: 245
Reputation: 1365
You can do multiple things for this.
METHOD 1
Disable the options: After the person has answered you can make the the sibling options disabled.
DOWNSIDE: the person can make the element enabled again by inspecting the element.
METHOD 2
Server side validation: check from server side if the answer has been answered or not on each call.
DOWNSIDE: server calls are increased.
METHOD 3
Remove the onclick along with onClick: After the person has answered you can make the the sibling options disabled AND remove the onClick call from them.
DOWNSIDE: Not sure of any yet.
EDIT 1
Server side validation is still important
Even after you do all those things above if the person really wants to be fishy they can still send answers to your server by calling the function from console.
suppose in the OnClick function of the option you are calling your storeAnwserStats(), and since they are client side JS files I can easily check it and send the request by going to the console and typing storeAnwserStats(question_id, answer_id) (and question ID can be seen in the network tab)
good luck!
Upvotes: 1