I need to get data from database and display it in a select/option based on input value of a chosen choice of an input picker plugin. I have this code in invoice.php:
<div class="form-group">
<input type="text" class="form-control form-control-sm" id="items" name="items" value="">
</div>
<div class="form-group">
<select class="form-select form-select-sm" id="uom" name="uom">
</select>
</div>
<script>
var myData = JSON.parse(
$.ajax({
method: "GET",
url: "parsers/items_select.php",
async: false
}).responseText);
$(document).ready(function () {
$('input#items').inputpicker({
data: myData,
fields:['itemNo','title'],
fieldText:'itemNo',
fieldValue:'id',
headShow: true,
filterOpen: true,
autoOpen: true
});
});
</script>
and this is items_select.php:
<?php
require_once '../init.php';
$data = [];
$q = ((isset($_GET['q']) && $_GET['q'] != '')?sanitize($_GET['q']):'');
$item_select = $db->query("SELECT id, itemNo, title FROM products");
while($item = mysqli_fetch_assoc($item_select)){
$data[] = $item;
}
echo json_encode($data);
?>
The input picker plugin works 100% fine.
Now I have did it perfectly if I use a regular select/option rather than input picker. Here is my code in invoice.php:
<?php
$itemQuery = $db->query("SELECT * FROM products ORDER BY title DESC");
?>
<div class="form-group">
<select class="form-select form-select-sm" id="items" name="items">
<option value=""<?=(($items == '')?' selected':'');?>></option>
<?php while($item = mysqli_fetch_assoc($itemQuery)): ?>
<option value="<?=$item['id'];?>"<?=(($items == $item['id'])?' selected':'');?>><?=$item['uom'];?></option>
<?php endwhile; ?>
</select>
</div>
<script>
function get_child_options(selected){
if(typeof selected === 'undefined'){
var selected = '';
}
var itemsID = jQuery('#items').val();
jQuery.ajax({
url: 'parsers/uom_select.php',
type: 'POST',
data: {itemsID : itemsID, selected: selected},
success: function(data){
jQuery('#uom').html(data);
},
error: function(){alert("Something went wrong with the child options.")},
});
}
jQuery('select[name="items"]').change(function(){
get_child_options();
});
jQuery('document').ready(function(){
get_child_options('<?=$uom;?>');
});
</script>
and in uom_select.php:
<?php
require_once '../init.php';
$itemsID = (int)$_POST['itemsID'];
$selected = sanitize($_POST['selected']);
$item_childQuery = $db->prepare("SELECT * FROM products WHERE id = ? ORDER BY uom");
$item_childQuery->bind_param('i', $itemsID);
$item_childQuery->execute();
$result = $item_childQuery->get_result();
ob_start(); ?>
<option value=""></option>
<?php while($item_child = mysqli_fetch_assoc($result)): ?>
<option value="<?=$item_child['id'];?>"<?=(($selected == $item_child['id'])?' selected':'');?>><?=$item_child['uom'];?></option>
<?php endwhile; ?>
<?php echo ob_get_clean();?>
But the above code will not work on input picker plugin, since it is not a select/option element and it displays data in divs and table. What is the solution?