我第一次在这里问问题,但多年来我很享受许多其他帖子的见解。我正在尝试根据用户从另一个字段中选择的内容来更新 HTML 表中的字段,但我需要通过 PHP 查询获取该值。这是我的代码:
HTML
<td style="width:25%;">
<?php
echo '<select onblur="CheckProduct()" id="GetProduct[]" name="GetProduct[]" required>';
echo '<option value =""></option>';
$sql = "SELECT ProdCode, ProdDescription, OrgCode, SKU FROM whproducts";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0 ) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='" . $row["ProdCode"] . "'>" . $row["ProdCode"] . " - " .
$row["ProdDescription"] . "</option>";
}
}
echo '</select>';
?>
</td>
<td style="width:25%;" id="Description"></td>
JAVASCRIPT
function CheckProduct() {
var pcode = $(this).closest('tr').find('GetProduct').val();
$.ajax({
url: 'checkproduct.php',
type: "POST",
data: {
'pcode': pcode;
},
success: function(data) {
$(this).closest('tr').find('Description').val(data);
alert(data);
}
});
}
PHP(检查product.php 文件)
<?php
$servername = "XXX";
$username = "XXX";
$password = "XXX";
$dbname = "XXX";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$code = $_POST['pcode'];
$sql = "SELECT ProdDescription FROM whproducts WHERE ProdCode='" . $code ."'";
$result = mysqli_query($conn, $sql);
echo $result;
?>
当我运行此命令时没有任何反应,并且我不确定是否确实可以将一些数据从 PHP 执行传递回 JavaScript/Ajax 函数。
代表!
我认为
<tbody id="myTable"
或<table id="myTable"
$(function() {
$('#myTable').on('change', '[name^=GetProduct]', function() { // name starts with GetProduct
const pcode = $(this).val();
const $desc = $(this).closest('tr').find('Description');
$.post('checkproduct.php',{ pcode }, function(data) { $desc.val(data); });
});
});