Ok guys, i finally managed to make it work properly ofc i had to change the code again but now it works mostly how i want.
index.php
<form role="form" method="post" action="">
<select id="products" name="products">
<?php
require 'bundle.php';
$products = loadProducts();
foreach ($products as $product) {
echo "<option id='".$product['id']."' value='".$product['id']."' selected>".$product['name']."</option>";
}
?>
</select>
<select id="bundles" name="bundles">
</select>
</form>
Script
<script type="text/javascript">
$(document).ready(function(){
$("#products").change(function(){
var pid = $("#products").val();
$.ajax({
url: 'data.php',
method: 'post',
data: 'pid=' + pid
}).done(function(bundles){
console.log(bundles);
bundles = JSON.parse(bundles);
$('#bundles').empty();
bundles.forEach(function(bundle){
$('#bundles').append('<option>' + bundle.name + '</option>')
})
})
})
})
</script>
bundle.php
<?php
require 'conection.php';
if(isset($_POST['pid'])) {
$db = new DbConnect;
$conn = $db->connect();
$stmt = $conn->prepare("SELECT * FROM bundles WHERE pid = " . $_POST['pid']);
$stmt->execute();
$bundles = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($bundles);
}
function loadProducts() {
$db = new DbConnect;
$conn = $db->connect();
$stmt = $conn->prepare("SELECT * FROM products");
$stmt->execute();
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $products;
}
?>
Ok so this is the code that works now, but i have some issues i still need help with:
1.) atm when i load the page it gets me the last option as selected but i want to have the first option selected w/o having to make an option first as <option selected="" disabled="">Select Product</option>
, i want the first option from list to be the first row from db as selected [Solved this part]
2.) how can i display the selected value in index.php because based on the values from the 2 lists i need to get a different value from a different table for example ( first list selected value is: prodname and second list selected is 7 now i need the 2 values to get a 3'rd value which is = prodname7)