添加多个选择框字段并使用Ajax将这些选择框值提交到PHP脚本并插入到Mysql表中 如何使用Jquery动态添加或删除动态选择框数据并使用带有验证的PHP使用Ajax插入到Mysql表中
选择框必须是动态的,例如类别和产品。根据产品下拉列表中显示的所有产品类别。
之后我可以添加更多下拉菜单,或者我们可以说3个字段的新div(div的副本),即2个下拉菜单和一个输入框,还可以选择删除带验证的div
这是我的代码:index.php
<script type="text/javascript" src="js/jquery.min.js"></script>
<?php include("db.php");?>
<div class="data">
Category :
<select name="category1" id="category1">
<option value=''>------- Select --------</option>
<?php
$sql = "select * from `categories`";
$res = mysqli_query($con, $sql);
if(mysqli_num_rows($res) > 0) {
while($row = mysqli_fetch_object($res)) {
echo "<option value='".$row->cat_id."'>".$row->cat_name."</option>";
}
}
?>
</select>
Products :
<select name="products1" id="products1">
<option>------- Select --------</option>
</select>
<input type ="text" name="price1" value="" placeholder="Price">
</div>
<a href="#">Add More</a>
<a href="#">Remove</a>
<script>
$(document).ready(function() {
$("#category1").change(function() {
var product_id = $(this).val();
if(product_id != "") {
$.ajax({
url:"get-products.php",
data:{product_id:product_id},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#products1").html(resp);
}
});
} else {
$("#products1").html("<option value=''>------- Select --------</option>");
}
});
});
</script>
GET-products.php
include("db.php");
if(isset($_POST['product_id'])) {
$sql = "select * from `products` where `cat_id`=".mysqli_real_escape_string($con, $_POST['product_id']);
$res = mysqli_query($con, $sql);
if(mysqli_num_rows($res) > 0) {
echo "<option value=''>------- Select --------</option>";
while($row = mysqli_fetch_object($res)) {
echo "<option value='".$row->product_id."'>".$row->product_name."</option>";
}
}
}else {
header('location: ./');
}