I am attempting to create a system that reads hints from a MySQL database, and displays them to the user at an appropriate time. However, I haven't managed to get the hints (VARCHAR
) to the JS variables to be displayed without exposing them in the HTML when viewed on the webpage. Here is my Code:
<?php
require_once ('config.php'); <!-- This connects to the database, all details are in the config.php -->
$result = $link->query ('SELECT `hint1`, `hint2`, `hint3`, `hint4`, `hint5`, `hint6`, `hint7` FROM `hints` WHERE `questNo` = 1');
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$hint1 = $row['hint1'];
$hint2 = $row['hint2'];
$hint3 = $row['hint3'];
$hint4 = $row['hint4'];
$hint5 = $row['hint5'];
$hint6 = $row['hint6'];
$hint7 = $row['hint7'];
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Help</title>
</head>
<body>
<!-- Start Hell -->
<div id="dom-target" style="display: none;">
<?php
echo htmlspecialchars($hint1);
?>
</div>
<script>
var div = document.getElementById("dom-target");
var hint1 = div.textContent;
</script>
(This would be repeated for all hints)
--------------------------------
(UNIMPORTANT HTML)
--------------------------------
<h2 style="text-decoration: underline;"> Hints<br></h2>
<br>
<h2 onclick="displayHint()" id="hint1">Click for hint</h2>
<br>
<h2 onclick="displayHint()" id="hint2">Click for hint</h2>
<br>
<h2 onclick="displayHint()" id="hint3">Click for hint</h2>
<br>
<h2 onclick="displayHint()" id="hint4">Click for hint</h2>
<br>
<h2 onclick="displayHint()" id="hint5">Click for hint</h2>
<br>
<h2 onclick="displayHint()" id="hint6">Click for hint</h2>
<br>
<h2 onclick="displayHint()" id="hint7">Click for hint</h2>
<br>
<script>
function displayHint() {
document.getElementById("hint1").innerHTML = hint1;
}
</script>
<style>
(Styling Elements)
</style>
</body>
</html>
This works for my purposes, but it shows the hints in the HTML of the actual website (due to the PHP's echo
), which I do not want. I have attempted AJAX (Point 1 in this tutorial How do I pass variables and data from PHP to JavaScript?, but the output did not work correctly, and displayed [object HTMLHeadingElement] when the text was clicked. The database elements are properly transferred in too, as I checked by echoing the PHP variables, and they are right.
Any help would be appreciated, Thanks :P