I'm working on a project with a classmate, neither of us have previous experience with php and javascript. Our goal is to query a db and store the results in an array then pass that array to a javascript function. My partner wrote this bit of code which works but I was unable to successfully pass the array to our function in our javascript.
First, I tried using a local array which worked out fine when I tested it. Then I tried with the array generated in the above php segment, I've seen this question asked a few times but when I tried implementing some of the suggestions to encode the array as a JSON object that didn't work. Is there something wrong with the way we store the results from the database? I appreciate any help.
<?php
$query = "SELECT * FROM predictions ORDER BY course_no DESC";
$result = $db->query($query);
if ($result and $result->num_rows != 0) {
@$result->data_seek(0);
while($classesArray = @$result->fetch_assoc()) {
extract($classesArray);
echo $course_no . "<br>";
}
@$result->free(); // Release memory for resultset
@$db->close();
echo " <script>var a = json_encode($classesArray);</script>";
}
?>
<script>
$(document).ready(function(){
//var a = ["class1", "class2", "class3"];
//loadClasses(a);'
loadClasses(a);
});
function loadClasses(classesArray) {
// #classesfield is the id of the classes dropdown
for (var i = 0; i < classesArray.length; i++) {
$("#classesdropdown").append('<input class="w3-check" type="checkbox">'); // add checkbox to our dropdown
$label = $('<label class="w3-validate"></label>'); // crete element to inject
$label[0].innerHTML= (classesArray[i]); // give it a class label
$("#classesdropdown").append($label); // add it to our dropdown
$("#classesdropdown").append('<br>'); // add new line to the dropdown
}
}
</script>
@chars in your code, they prevent error reporting and you will not be able to know if you have some errors in your code or not. What exactly is the problem?loadClassesfunction? what is the actual output (the final html) you have?