I am developing a Javascript game and need to implement PHP for a database. Before the PHP the code worked but since I later wanted to add database to it I began testing different things. My PHP is inside the same page as the HTML but the Javascript is in an external file. I would like to make it so when the Javascript changes the score using its own variables it also activates the PHP to update the database variable. Any help?
function checkAnswer(q, n, button) {
var CA = QA[q].correctAnswer;
var BA = button.value;
disableButtons(n);
if (BA == CA) {
correct++;
correctAnswer();
} else if (BA != CA) {
wrongAnswer(QA[q].correctAnswer);
} else {
console.log("Error");
}
score();
}
function score() {
var scoreText = document.getElementById("score");
var score = "<?php scoreChange('" + correct + "'); ?>";
scoreText.innerHTML = score + "/20";
}
<?php
//Database Connection
require("../connection/connect.php");
//Start Session
session_start();
$logged_in = $_SESSION['logged_in'];
$user = $_SESSION['usr_id'];
$scienceScore = 0;
$scoreReset = 0;
if ($scoreReset == 0) {
$query = $con->query("UPDATE users SET science='0' WHERE username='$user'");
$scoreReset = 1;
}
//Change Score
function changeScore($correct) {
$scienceScore = $correct;
$query = $con->query("UPDATE users SET science='$scienceScore' WHERE username='$user'");
$_SESSION['science'] = $scienceScore;
echo $scienceScore;
}
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="game">
<div id="top">
<div class="title">
<div id="left">
<h2>STEM Science Questions</h2>
<p>Get the questions right and score points to be on the scoreboard!</p>
</div>
<div id="right">
<h1 id="score">0/20</h1>
</div>
</div>
</div>
</div>
-The JS is in an external file linked with the tags-
If more code is needed then I will post more!