使用 jquery 将选中的复选框 ID 发送到数据库



我有一个清单,用户需要选中多个复选框,然后我应该计算每个复选框的总价格并显示它。问题是我应该将选中的复选框插入数据库。因此,当我使用 isset(( 函数时,我遇到了错误。所以我正在考虑使用 jquery 代替并将检查的 id 发送到数据库,但我不知道该怎么做。

<form method="post" action="#">
<div class="agileinfo_services_grids">
<?php 
$sql = "SELECT * FROM services";
$result = mysqli_query($connection, $sql);
$num_rows = mysqli_num_rows($result);
if($num_rows > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$price = $row['price'];
$id = $row['id'];
echo "<div class='col-md-4 agileinfo_services_grid'>
<div class='agileinfo_services_grid1'>
<div class='price'><h3>$" . $row['price'] . "</h3></div>
<h4>" . $row['title'] . "</h4>
<p>" . $row['details'] . "</p>
<div class='agileinfo_services_grid1_pos'>
<input id='$id' name:'checkbox[]' class='icon-checkbox my-activity' type='checkbox' value='$price'/>
<label for='$id'>
<span class='glyphicon glyphicon-unchecked unchecked'></span>
<span class='glyphicon glyphicon-check checked'></span>
</label>
</div>
</div>
</div>";            
} 
} else {
echo "No Current Services Available";
}
?>
</div>
<div class="total">
<div class="total-left">
<p>Total :<span>$<input type="text" id="amount" readonly></span>
</div>
<div class="total-right">
<input type="submit" value="Check Out" name="submit">
</div>
<div class="clear"> </div>
</div>
</form>

下面是我用来计算复选框总价的函数。如何修改它以将复选框的 ID 也发送到数据库。

<script type="text/javascript">
$(document).ready(function() {        
$(".my-activity").click(function(event) {
var total = 0;
$(".my-activity:checked").each(function() {
total += parseInt($(this).val());
$.post("services.php", {id: this.id, checked:this.checked});
});
if (total == 0) {
$('#amount').val('');
} else {                
$('#amount').val(total);
}
});
});    
</script>

按照以下步骤将选定的 ID 发送到数据库。

.HTML:

<div id="checkboxes">
<input id="chkbx_0" type="checkbox" name="c_n_0" checked="checked" />Option 1
<input id="chkbx_1" type="checkbox" name="c_n_1" />Option 2
<input id="chkbx_2" type="checkbox" name="c_n_2" />Option 3
<input id="chkbx_3" type="checkbox" name="c_n_3" checked="checked" />Option 4
</div>

使用此jquery脚本:

var selected_ids = [];
$('#checkboxes input:checked').each(function() {
selected_ids.push($(this).attr('id'));
});
/* to sending ids to database using ajax */
$.ajax({  
type: 'POST',  
url: 'test.php', 
data: { selected_ids: selected_ids },
success: function(response) {
alert(response);
}
});

最新更新