It seems like you want to implement the dynamic category and subcategory dropdown using AJAX in PHP. However, the provided code is a bit incomplete as it references some files and functions that are not included here. Additionally, the subcategory selection code could be improved. Let's correct and optimize the code:
1. Modify the form to add an ID attribute to the "subcategory" select element:
```php
<label class="col-sm-3 col-form-label">Subcategory</label>
<div class="col-sm-9">
<select name="subcat_id" id="subcategory" class="form-control basic" required>
<option value="">--Select Subcategory--</option>
</select>
</div>
```
2. Create a new PHP file named `get_subcategories.php` to handle the AJAX request and fetch subcategories based on the selected category:
```php
// get_subcategories.php
<?php
// Include your database connection here
$mysqli = new mysqli("localhost", "username", "password", "database_name");
if (isset($_POST['id'])) {
$categoryId = $_POST['id'];
// Fetch subcategories based on the selected category
$subcat_qry = "SELECT * FROM tbl_subcategorys WHERE category_id = $categoryId ORDER BY subcategory_name";
$subcat_result = mysqli_query($mysqli, $subcat_qry);
$subcategories = array();
while ($subcategory = mysqli_fetch_assoc($subcat_result)) {
$subcategories[] = $subcategory;
}
// Return the subcategories in JSON format
echo json_encode($subcategories);
exit;
}
?>
```
3. Finally, update the JavaScript function in the `index.php` file to handle the AJAX call and update the subcategory dropdown:
```javascript
// index.php
<script>
function get_subcategorybyval() {
var id = $("#cat_id :selected").val();
$.ajax({
url: 'get_subcategories.php',
type: 'post',
data: { id: id },
dataType: 'json',
success: function(data) {
var subcategoryDropdown = $("#subcategory");
subcategoryDropdown.empty();
subcategoryDropdown.append('<option value="">--Select Subcategory--</option>');
$.each(data, function(key, value) {
subcategoryDropdown.append('<option value="' + value.cid + '">' + value.subcategory_name + '</option>');
});
},
error: function(xhr, status, error) {
console.error(error);
}
});
}
$(document).ready(function() {
// Event listener for category dropdown change
$("#cat_id").on("change", function() {
get_subcategorybyval();
});
// Load subcategories if category is pre-selected (for edit)
$("#cat_id").trigger("change");
});
</script>
```
With these modifications, the dynamic category and subcategory dropdowns should work as expected. When you select a category, the subcategory dropdown will be populated with the relevant subcategories fetched from the database using AJAX.
0 Comments