fix: fixing score bug

This commit is contained in:
Carolus Bramnatyo Seno Mahesworo 2025-12-01 12:13:20 +07:00
parent dfd725d1b1
commit 4ee2118096
2 changed files with 28 additions and 14 deletions

View File

@ -66,7 +66,7 @@ function selectAnswer(e){
const isCorrect = selectedBtn.dataset.correct === "true"; const isCorrect = selectedBtn.dataset.correct === "true";
if(isCorrect){ if(isCorrect){
selectedBtn.classList.add("correct"); selectedBtn.classList.add("correct");
score++; score += 10;
} else { } else {
selectedBtn.classList.add("Incorrect"); selectedBtn.classList.add("Incorrect");
} }
@ -83,8 +83,6 @@ function showScore(){
resetState(); resetState();
const show = questionElement.innerHTML = `you scored ${score} out of ${questions.length}!`; const show = questionElement.innerHTML = `you scored ${score} out of ${questions.length}!`;
postScore(score); postScore(score);
alert(show);
window.location.href = "../leaderboard.php"
} }
function handleNextBtn(){ function handleNextBtn(){
@ -108,10 +106,21 @@ function postScore(score){
fetch('/score.php', { fetch('/score.php', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ score }) body: JSON.stringify({ score: score })
}) })
.then(r => r.text()) .then(r => r.json())
.then(t => console.log("Server response:", t)) .then(data => {
.catch(err => console.error("Fetch error:", err)); console.log("Server response:", data);
if(data.success || data.message === "Score accumulated") {
window.location.href = "../leaderboard.php";
} else {
window.location.href = "../leaderboard.php";
}
})
.catch(err => {
console.error("Fetch error:", err);
alert("Terjadi kesalahan koneksi.");
});
} }
startQuiz() startQuiz()

View File

@ -19,15 +19,20 @@ if (!$user_id) {
exit; exit;
} }
$stmt = $db->prepare("INSERT INTO scores (id, score) VALUES (?, ?)"); $sql = "UPDATE users SET score = score + ? where id =? ";
$stmt->bind_param("ii", $user_id, $score); $stmt = $db ->prepare($sql);
if ($stmt->execute()) { if ($stmt){
echo json_encode(["success" => true]); $stmt->bind_param("ii",$score,$user_id);
} else { if($stmt->execute()){
echo json_encode(["error" => "insert failed"]); echo json_encode(["success" => true, "message" => "Score accumulated"]);
}else{
echo json_encode(["error" => "update failed: " . $stmt->error]);
}
$stmt->close();
}else{
echo json_encode(["error" => "stetment prep failed"]);
} }
$stmt->close();
$db->close(); $db->close();
?> ?>