I’m facing an issue that I have created 2 tables one is parent_category and another is child_category. I fetch the parent categories in select option drop down.
My aim is to fetch the child category from child table with parent id that is same in both table. I have tried many time but when I select parent category it will show me the same name categories many time in child select option drop down.
Here is my code.
index.php
<div>
<select id="parent_category">
<?php
$select = "select * from categories";
$run = mysqli_query($con, $select);
while($row = mysqli_fetch_array($run)){
echo "<option value='".$row['id']."'>".$row['name']."</option>";
}
?>
</select>
<br><br>
<select id="child_category">
</select>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$('#parent_category').on('change', function() {
let id = $(this).find(':selected').data('id');
alert(id);
$.ajax({
url: 'data.php',
method: 'GET',
data: {
id: id,
},
success: function(data) {
$("#child_category").html(data);
}
});
});
});
</script>
data.php
$con = mysqli_connect("localhost", "root", "", "nilam-ghar");
if(isset($_GET["id"])){
$output = "";
$id = $_GET['id'];
$get = "SELECT * FROM child_category WHERE parent_cat_id='$id'";
$run = mysqli_query($con, $get);
while($row = mysqli_fetch_array($run)){
echo $output .= '
<option>'.$row["name"].'</option>;
';
}
echo $output;
}
database tables
parent_category:
id(int) date(date) name(text)
child_category:
id()int date(date) parent_cat_id(int) name(text)
**Note:** data exits in both table. in child category, parent id also exist.
2
Answers
just checked your code found issue here
let id = $(this).find(':selected').**data('id');**
data(‘id’) this will use when you assign<option data-id="1">OptionA</option>
like this in your case your case you have used value attribute of option soyou will get value like this.
Also you can checkout below snippet, having more clear vision.
Two things seems to be wrong in your code.
First, in your JavaScript you’re getting the
data-id
attribute to make the query, but your<option>
s don’t have this attribute. So, try changingfor
Also, in your data.php, it seems that you’re echoing the output twice, so try the following: