I have the following backend code, it is displaying the data correctly:
<?php
include ("_inc_dbvars.php");
$idu = 2; // These variables i get from $_SESSION, for simplicity I made them static.
$idm = 2; //
$result_total=0;
$result_max=0;
$zero_count = 0; // Count of answer values that are 0
$non_zero_count = 0; // Count of answer values that are not 0
$row_count = 0;
$result_total = 0;
$result_max = 0;
$score = 0;
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * from user_answer_values where user_id=:idu and module_id=:idm");
$stmt->bindParam(':idu', $idu);
$stmt->bindParam(':idm', $idm);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row_count++;
if ($row['answer_value'] == 0) {
$zero_count++;
} else {
$non_zero_count++;
$result_total = $result_total + $row['answer_value'];
}
}
$result_max = $row_count * 5;
$score = round(($result_total / $result_max) * 100);
$hdi = round(($result_total / $result_max)*200);
$reliability = round(($non_zero_count / $row_count) * 100);
$color_score = "#FFF";
$data = array(
"Max" => htmlspecialchars($result_max, ENT_QUOTES, 'UTF-8'),
"Score" => htmlspecialchars($result_total, ENT_QUOTES, 'UTF-8'),
"ScorePercent" => htmlspecialchars($score, ENT_QUOTES, 'UTF-8'),
"Reliability" => htmlspecialchars($reliability, ENT_QUOTES, 'UTF-8'),
"HDI" => htmlspecialchars($hdi, ENT_QUOTES, 'UTF-8')
);
header('Content-Type: application/json');
echo json_encode($data);
} catch(PDOException $e) {
$data = array(
"Error" => "Connection failed: " . $e->getMessage()
);
echo json_encode($data);
}
?>
The data:
{
"Max": "295",
"Score": "119",
"ScorePercent": "40",
"Reliability": "81",
"HDI": "81"
}
This is the JS request
let hxttp = new XMLHttpRequest();
hxttp.onreadystatechange = function() {
console.log(this.readyState);
if (this.readyState == 4 && this.status == 200) {
let data = JSON.parse(this.responseText);
console.log(data);
}
};
hxttp.open("GET", "../include/_inc_score.php", true);
hxttp.send();
The "../include/_inc_score.php"
is the correct file location.
I have 7 individual modules that all need to access their scores. I use JS to render them individually and responsively. Can't seem to get the JSON data.
Network tab from console: https://imgur.com/a/HA94SZo
Remember kids, double check the console and see if you're looking in the correct section of the Console. I was in the Error section and didn't even see that the data was displaying correctly.