I have 2 selects, where the second one should be populated based on what is selected in the first one. But I can't fully get it to work.
If I use dataType: 'Json'
in the call, it get a parser error, and if I remove I can get it to perform the empty part on the test select. So I must have some kind of parsing error, and I can't get it to append to the test select. How do I solve these issues?
The first one is created like this:
<select
size="1"
id="farvestandard"
name="farvestandard"
class="listform ays-ignore" style="width: 155px;">
<?php
$farveid = $res['r54'];
$farvesql = "select * from farvekoder group by farvestandard";
$farvequery = mysql_query("$farvesql") or die(mysql_error);
while($farverow = mysql_fetch_array($farvequery, MYSQL_ASSOC)) {
$select = '';
if ($farverow['farvestandard'] == $res['farvestandard'])
$select = ' selected';
?>
<option
value="<?php echo $farverow['farvestandard']; ?>"
<?php echo $select; ?>>
<?php echo $farverow['farvestandard']; ?>
</option>
<?php
}
?>
</select>
and the second one, which should be populated depending on the selection in the first one.
<select name="test" id="test">
<option value="">-- select one -- </option>
</select>
JQuery script
<script>
$("#farvestandard").change(function() {
var farvestandardID = $(this).val();
if (farvestandardID) {
$.ajax({
url: "/farvekoderajax.php",
dataType: 'Json',
data: {
'id': farvestandardID
},
success: function(data) {
console.log("success");
$('select[id="test"]').empty();
$('select[id="test"]').append('<option value="">Vælg farvekode</option>');
$.each(data, function(key, value) {
$('select[id="test"]').append('<option value="' + key + '">' + value + '</option>');
});
},
error: function(data, error) {
console.log(arguments);
}
});
}
});
</script>
and last the farvekoderajax.php page
<?php
require('system/global_defs.php');
$mysqli = new mysqli($MYSQL_DEFS["host"],$MYSQL_DEFS["user"],$MYSQL_DEFS["password"], $MYSQL_DEFS["db"]);
echo $sql = "SELECT * FROM farvekoder WHERE farvestandard LIKE '%".$_GET['id']."%' AND inaktiv = 0 AND status = 3 ORDER BY farvekode ASC";
$result = $mysqli->query($sql);
$json = [];
while($row = $result->fetch_assoc()){
$json[$row['id']] = $row['farvekode'];
}
echo json_encode($json);
return json_encode($json);
?>
If I open farvekoderajax.php with variable, I'll get this result:
{
"3": "3009",
"1": "7015",
"34": "7021",
"25": "7024",
"4": "7035",
"2": "7046"
}
Can't see what's wrong with that, and that is what it should populate test with.
If I remove datatype:json
I get this below error :
TypeError: right-hand side of 'in' should be an object, got string