I don't have a lot of experience with Javascript and Ajax or JSON for that matter but I'm currently building an HTML lookup tool for a simple PostgreSQL database and I'm a little stuck here. I want to fill the selectbox on the right with corresponding form names from our database whenever the user selects the study in the left selectbox However, I have problems to process the array that I get back from the PHP script.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery/3.2.1.min.js"</script>
<script>
function getselect(value) {
$.ajax(
{
type: "GET",
url: 'getforms.php',
data: {value: value},
dataType: "json",
success: fillbox
});
}
function fillbox(data) {
var forms = $('#forms');
var arr = $.parseJSON(data);
for (var x = 0; x < arr.length; x++) {
forms.append(new Option(arr[x]));
}
}
</script>
</head>
<body>
[...]
<?php
$snames = $conn->prepare("SELECT DISTINCT studienname FROM public.fulldict");
$snames->execute();
$a=$snames->fetchAll(PDO::FETCH_COLUMN, 0);
?>
<table border="0">
<tr>
<th>Studien:</th>
<th>Formulare:</th>
</tr>
<tr>
<td>
<select id="study" name="Studien" size="12" onchange="getselect(this.value);">
<?php foreach($a as $option) { ?>
<option value="<?php echo $option ?>"> <?php echo $option ?> </option>
<?php }?>
</select>
</td>
<td>
<select id="forms"></select>
</td>
</tr>
</table>
?>
</body>
</html>
The getforms.php is intended to handle the SQL-query and send an array of values from the database back to Javascript, where the 'fillbox' function is supposed to fill the select box with the values from the array.
<?php
$f = $_GET['value'];
// Connect to Database
require_once 'dbconfig.php';
$dsn = "pgsql:host=$host;port=5432;dbname=$db;user=$username;password=$password";
$conn = new PDO($dsn);
// Get array with form names
$form_arr=array();
$fnames = $conn->prepare("SELECT DISTINCT formular FROM public.fulldict WHERE studienname = '$f'");
$fnames->execute();
$form_arr=$fnames->fetchAll(PDO::FETCH_COLUMN, 0);
echo json_encode($form_arr);
?>
When I run the code and select anything from the first selectbox nothing happens. Am I doing something wrong accessing the second selectbox?
Any help is appreciated.