Dependent dropdown get selected values

index.php

<form role="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="products">Product</label>
<select id="products" name="products" class="user">
<?php 
	require 'data.php';
	$products = loadProducts();
	foreach ($products as $product) {
	echo "<option id='".$product['id']."' value='".$product['id']."' selected>".$product['name']."</option>";
}
?>
</select>
<label for="bundles">Bundle</label>
<select id="bundles" name="bundles">
</select>
</form>

Script

	<script type="text/javascript">
		$(document).ready(function(){
			$("#products").change(function(){
				var aid = $("#products").val();
				$.ajax({
					url: 'data.php',
					method: 'post',
					data: 'aid=' + aid
				}).done(function(bundles){
					console.log(bundles);
					bundles = JSON.parse(bundles);
					$('#bundles').empty();
					bundles.forEach(function(bundle){
						$('#bundles').append('<option>' + bundle.name + '</option>')
					})
				})
			})
		})
	</script>

data.php

<?php 
	require 'DbConnect.php';


	if(isset($_POST['aid'])) {
		$db = new DbConnect;
		$conn = $db->connect();

		$stmt = $conn->prepare("SELECT * FROM bundles WHERE pid = " . $_POST['aid']);
		$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;
	}

 ?>
</select>
<label for="bundles">Bundle</label>
<select id="bundles" name="bundles">
</select>
</form>

Ok so i have this dependent drop down lists which works fine but i need help with 2 problems

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

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)

Look at this rule. It sets any option as selected. You should change this so that only one or no option will be set to selected. If you really want to select the first item in any case:

$sel = ' selected';
foreach ($products as $product) {
    echo '<option id="'.$product['id'].'" value="'.$product['id'].'"' . $sel . '>' . $product['name'] . '</option>';
    $sel = '';
}

Hello and thank you for replying, the problem is that what i want is that atm my first product shows up first anyway but the problem is that the second list doesn’t show the values that it needs for the product unless i change the product and change it back to first product … anyway what about the 2nd problem … because atm if i write echo $product[‘name’]; it echoes the last product from the list

just to mention im quite new at php but even newer at js so pls don’t flame me to much :smiley: and yeah any help it’s much appreciated

The easy fix for that is to give a default value in the first drop down so it triggers the call to change the second.

This is not a prepared statement.

It should be this,

		$stmt = $conn->prepare("SELECT * FROM bundles WHERE pid = ?");
		$stmt->execute([$_POST['aid']]);

thanks for the reply but that doesn’t answer my questions … ik that if i make a first selection that would solve question 1 , but as i stated i need the first option to be the first product and be as selected so the second list can show it’s values for that product , the problem is that ik that the current js works on change but i just wondered if there is any other way to accomplish what i wanted because whatever i tried didn’t work and didn’t manage to find anything helpful around the net.

Then you also need to call the javascript function onload with the current selected value.

well thank with you tip i managed to make it work so that second list shows the value too once the page its loaded with the first product.

<script type="text/javascript">
	$(document).ready(function(){
		$("select#products").change(function(){
			var aid = $("select#products option:selected").val();
			$.ajax({
				url: 'data.php',
				method: 'post',
				data: 'aid=' + aid
				}).done(function(bundles){
				console.log(bundles);
				bundles = JSON.parse(bundles);
				$('#bundles').empty();
				bundles.forEach(function(bundle){
					$('#bundles').append('<option>' + bundle.name + '</option>')
				});
			});
		}).change();
	});
</script>

now if anyone can actually help me with how to get the values to show up i would really appreciate coz atm if i echo $product[‘name’]; it echoes the last option from the list regardless of what i do… i really need help with getting the 2 values from the lists so pls help me out.

Is this supposed to be coming from the database?

Don’t do select *, name the columns you want returned.

yes the data is populated from DB , sorry but i don’t understand what it has select * has to do with being able to get the selected values displayed in the index.php

my DB looks like this:
products:
id,name
bundles:
id,pid,name

As a general rule to follow, you should always specify the columns you want, you should never select everything in a query.

how to get the values to show where? In the drop down? Where it should be processed?

1 Like

no i needed to get a variable for the selected option outside of dropdown so i can use that variable for other stuff and i managed to do that but only as $prod = selected product’s value which is fine it did help me progress on the stuff i want to accomplish now my only problem left so i can finish this project is that i have a list of prices for each of the products from the list (each prices has a variable) but now i only need a way to assign those price variables to the selected product

just for info:
prices DB looks like:
id,prod1,prod2,prod3,etc
1,price1,price2,price3,etc

then the products db(from where the drop down is generated) looks like:
id,name
1,prod1
2,prod2
3,prod3
etc

so i think i should go like this:

<?php

$prodprices = [
[1,$TSprice],
[2,$ESSprice],
[3,$ASBB],
[4,$MSBB],
// etc
];

foreach($prodprices as $prodprice){
if($prodval = $prodprice[0]) $pprice = $prodpice[1];
}

?>

where $TS/$ESS/$ASBB/$MSBBprice are the variables of the prices and $prodval is the variable for the selected product option from list… but i don’t think this is gonna work like this …

I’m still confused. What I am understanding is, you select a product. That product needs to be assigned to a bundle to price it? So what you are looking for is a way to send a product id and a bundle id to the database to store them as a group?

no no , what i need is just to get a variable from the selected Product from list which is assigned to the price of that product.

For example i select the product: product1

which returns me a variable of $prodval which is = 1(product1’s ID) so now i need somehow to get a variable let’s call it $prodprice which is = product1’s price (or any of the selected product’s price)

You are not getting a variable, you are getting a value to assign to a variable.

So if you have productCode = 1 coming from somewhere. Is productPrice coming from a dropdown?

yeah the value of product is assigned to a variable which is $prodval like i said and no the productPrice is not coming from dropdown but from a table from DB

prices DB looks like:
id,prod1,prod2,prod3,etc
1,price1,price2,price3,etc

then the products db(from where the drop down is generated) looks like:
id,name
1,prod1
2,prod2
3,prod3
etc

Why are there multiple prices?

When you have the product, you now need to query for the prices (need it answered why there are multiple options).

So you can understand better please visit this page: website , as you will be able the see on the left i have all the prices displayed in input fields for being able to update them hence the “multiple” prices , there is 1 price for each product, and as you will see “Off Mrk. Sell:” there i need a code which is : (product price) * (bundle value) … in this case bundle value its fine i get the value i need i just need the product price of the selected product.

Basically when i select a product and a bundle from the drop down list my page will show information based on the selections.

So far i managed to make it work for : SS Req.: ; MS Req.: ; SO Req.: ; EO Req.: , Craft Cost: ; Prod. Cost: and Mrk. Fee: … so for the rest of the fields to work i need to make the Off Mrk. Sell: field like i said because the other field’s formulas work based on the value for this.

Edit:

Anyway what i need is something like this:

<?php
$val1 = "10";
$val2 = "20";
$val3 = "30";
$prod = "2";

$array1=array("1" => $val1, "2"=> $val2, "3" => $val3);
if (in_array($prod,$array1))
{
foreach ($array1 as $result) {
     $bla = $result;
     echo  $bla;
    
}
} 
else
{
    $bla = 0;
echo $bla;
}
?>

but this returns 0 instead of 20

There are errors galore in that html…

You need to tie the value in the select to the input.

Sponsor our Newsletter | Privacy Policy | Terms of Service