From 4ee2118096af2da2fe3faa73fce0e6b9c12df3d8 Mon Sep 17 00:00:00 2001 From: Carolus Bramnatyo Seno Mahesworo Date: Mon, 1 Dec 2025 12:13:20 +0700 Subject: [PATCH] fix: fixing score bug --- src/js/firstperson.js | 23 ++++++++++++++++------- src/score.php | 19 ++++++++++++------- 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/src/js/firstperson.js b/src/js/firstperson.js index c3d702f..eeaf632 100644 --- a/src/js/firstperson.js +++ b/src/js/firstperson.js @@ -66,7 +66,7 @@ function selectAnswer(e){ const isCorrect = selectedBtn.dataset.correct === "true"; if(isCorrect){ selectedBtn.classList.add("correct"); - score++; + score += 10; } else { selectedBtn.classList.add("Incorrect"); } @@ -83,8 +83,6 @@ function showScore(){ resetState(); const show = questionElement.innerHTML = `you scored ${score} out of ${questions.length}!`; postScore(score); - alert(show); - window.location.href = "../leaderboard.php" } function handleNextBtn(){ @@ -108,10 +106,21 @@ function postScore(score){ fetch('/score.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ score }) + body: JSON.stringify({ score: score }) }) - .then(r => r.text()) - .then(t => console.log("Server response:", t)) - .catch(err => console.error("Fetch error:", err)); + .then(r => r.json()) + .then(data => { + 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() \ No newline at end of file diff --git a/src/score.php b/src/score.php index 9a9ab6e..97421af 100644 --- a/src/score.php +++ b/src/score.php @@ -19,15 +19,20 @@ if (!$user_id) { exit; } -$stmt = $db->prepare("INSERT INTO scores (id, score) VALUES (?, ?)"); -$stmt->bind_param("ii", $user_id, $score); +$sql = "UPDATE users SET score = score + ? where id =? "; +$stmt = $db ->prepare($sql); -if ($stmt->execute()) { - echo json_encode(["success" => true]); -} else { - echo json_encode(["error" => "insert failed"]); +if ($stmt){ + $stmt->bind_param("ii",$score,$user_id); + if($stmt->execute()){ + 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(); ?> \ No newline at end of file