I’m developing an online quiz that would let the user answer questions by clicking on a few radio buttons. I want the program to use the questions that are in the database. I’ve already created the connection through PHP but it’s not properly passing through to the javascript code.
JavaScript
x
<body>
<?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'psych';
$connect = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
$res = mysqli_query($connect, "SELECT questions FROM questions") or die( mysqli_error($connect));
;
$quests = mysqli_fetch_array($res);
// echo "Quest0=$quests[0]";
$scores=array();
$i = "0";
while($row = mysqli_fetch_array($res))
{
$arr[$i] = $row['questions'];
$i++;
}
?>
<div id="quiz"></div>
<br>
<button id="submit">Calculate</button>
<h4 id="message"></h4>
<br><br>
<div id="results"></div>
<script type="text/javascript">
const submitButton = document.getElementById('submit');
const array = <?php echo json_encode($arr); ?>;
// Display the array elements
for(var i = 0; i < array.length; i++){
const myQuestions=[ {(array[i])}];
//document.write(myQuestions[i]);
//console.log(myQuestions[j]);
displayArrayObjects(myQuestions);
}
function displayArrayObjects(arrayObjects) {
var len = arrayObjects.length, text = "";
for (var i = 0; i < len; i++) {
var myObject = arrayObjects[i];
for (var x in myObject) {
text += ( myObject[x] );
}
text += "<br/>";
}
document.getElementById("message").innerHTML = text;
}
//const Myanswers = [a: "answer A", b: "answer B" ];
const answers = [{ answers: {
a: "answer A",
b: "answer B"
},
answerA: "a",
answerB: "b"
},];
Advertisement
Answer
You have some syntax errors.
JavaScript
<body>
<?php
$arr = array('q1','q2','q3');
?>
<div id="quiz"></div>
<br>
<button id="submit">Calculate</button>
<h4 id="message"></h4>
<br><br>
<div id="results"></div>
<script type="text/javascript">
const submitButton = document.getElementById('submit');
const array = <?php echo json_encode($arr); ?>;
let myQuestions = [];
// Display the array elements
for(var i = 0; i < array.length; i++){
myQuestions.push(array[i]);
//document.write(myQuestions[i]);
}
console.log(myQuestions);
displayArrayObjects(myQuestions);
function displayArrayObjects(arrayObjects) {
var len = arrayObjects.length, text = "";
for (var i = 0; i < len; i++) {
var myObject = arrayObjects[i];
for (var x in myObject) {
text += ( myObject[x] );
}
text += "<br/>";
}
document.getElementById("message").innerHTML = text;
}
//const Myanswers = [a: "answer A", b: "answer B" ];
const answers = [{ answers: {
a: "answer A",
b: "answer B"
},
answerA: "a",
answerB: "b"
},];
</script>