So I am trying to populate a category, sub category and vendor dropdown menu for a backend and im trying to use ajax. When I select a category the subcategories do not populate and there is no console errors.
dropdown.js
$(document).ready(function() {
$(document).on('change','#catid', function() {
var catid = $(this).val();
if(catid != "") {
$.ajax({
url:"get_data.php",
type:'POST',
data:{catid:catid},
success:function(response) {
//var resp = $.trim(response);
if(response != '') {
$("#subcatid").removeAttr('disabled','disabled').html(response);
$("#vendorid").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
}
else $("#subcatid, #vendorid").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
}
});
} else {
$("#subcatid, #vendorid").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
}
});
$(document).on('change','#subcatid', function() {
var subcatid = $(this).val();
if (subcatid != "") {
$.ajax({
url:"get_data.php",
type:'POST',
data: { subcatid: subcatid},
success:function(response) {
if (response != '')
$("#vendorid").removeAttr('disabled','disabled').html(response);
else $("#vendorid").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
}
});
} else {
$("#vendorid").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
}
});
});
I am not sure that this code is completely correct as I tried to convert my code from sqli to PDO which may be what broke the code but I am not sure if that is what it is because the js still doesn't seem to make anything change. get_data.php:
<?php
include_once "../header.php";
if (isset($_POST['catid'])){
$sql = "select * from subcategories where catid =" . $_POST['catid'];
$stmt = $pdo->prepare($sql);
$stmt->execute();
$data = $stmt->fetch();
$stmtCount = $stmt->rowCount();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmtCount >= 1) {
echo 'option value="">------- Select -------</option>';
foreach ($result as $row) {
echo "<option value='" . $row['subcatid'] . "'>" .
$row['subcatname'] . "</option>";
}
} else {
echo '<option value="">No Record</option>';
}
} else if (isset($_POST['subcatid'])) {
$sql = "select * from vendors where subcatid =" . $_POST['subcatid'];
$stmt = $pdo->prepare($sql);
$stmt->execute();
$data = $stmt->fetch();
$stmtCount = $stmt->rowCount();
if ($stmtCount >= 1) {
echo 'option value="">------- Select -------</option>';
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
echo "<option value='" . $row['vendorid'] . "'>" . $row['vendorid']
. "</option>";
}
} else {
echo '<option value="">No Record</option>';
}
}
?>