![](/img/trans.png)
[英]mysql query data not correctly being passed to javascript from php via ajax
[英]JavaScript Array not being passed to PHP via AJAX
我知道这个线程之前已经多次发布,但出于某种原因,我似乎可以将发布的解决方案应用于我的代码。 在此代码中,我试图在用户选择复选框时从表中删除一行。 (表格中的每一行都有一个复选框和一个 ID)
我收集了 javascript 数组中选定复选框的所有 ID,并通过 Ajax 将它们传递给 PHP。
当我尝试打印 $delete 数组的元素时,注意正在发生。 ,我知道 JS 数组现在是空的,因为我可以在控制台中打印值。
<?php
$link = mysqli_connect("localhost","xxxx-xxx", "x.xxxxx","xxx-xxx");
if($_POST['delete']){
$delete= json_decode($_POST['deleted']);
//Trying to print the values passed
foreach($x as $delete){
echo "<script>alert(".$x.");</script>";
}
}
}
?>
<form method="post">
<table id="secondDiv" class="table table-bordered">
<tr>
<th >
<form><input class="checkbox"type="checkbox" name="selectAll"id="selecctall" value=""></form>
</th>
<th>Date</th>
<th>Event</th>
<th>Details</th>
<th>Time & Location</th>
</tr>
<?php
$link = mysqli_connect("localhost","xxxx-xxx", "x.xxxxx","xxx-xxx");
$query = "SELECT * FROM meetings";
if($result = mysqli_query($link,$query)){
while($row = mysqli_fetch_array($result)){
// echo($row[0] + " " +$row[1] + " " + $row[2] + " " + $row[3]);
echo "<tr>";
echo "<td><form ><input class=\"checkbox1\" type=\"checkbox\" name=\"".$row['meetingNo']."\" >
</form></td>";
echo "<td>".$row['date']."</td>";
echo "<td>".$row['event']."</td>";
echo "<td>".$row['details']."</td>";
echo "<td>".$row['location']."</td>";
echo "</tr>";
}
}
//echo "hello world";
?>
</table>
<!-- <input type="submit" class="btn btn-warning" value="Edit" /> -->
<input onclick ="toPHP()" type="submit" class="btn btn-danger" name ="delete" value="Delete" />
</form>
//Event Listeners--work fine
var toDelete = new Array();
$(document).ready(function() {
$('#selecctall').click(function(event) { //on click
if(this.checked) { // check select status
$('.checkbox1').each(function() { //loop through each checkbox
this.checked = true; //select all checkboxes with class "checkbox1"
});
}else{
$('.checkbox1').each(function() { //loop through each checkbox
this.checked = false; //deselect all checkboxes with class "checkbox1"
});
}
});
});
$('input:checkbox').change(
function(){
if ($(this).is(':checked')) {
//alert(this.name);
toDelete.push(this.name);
}
return true;
});
//This function is supposed to send the toDelete array to PHP
//It is called when the user clicks delete
function toPHP(){
for(var index = 0; index < toDelete.length; index++)
console.log(toDelete[index]);
var stringed = JSON.stringify(toDelete);
$.ajax(
{
type: "POST",
url: "meetings.php",
contentType: "application/json",
data: {deleted: stringed }
}
);
return true;
}
你有你的 foreach 向后,没有第二个参数的json_decode
会给你一个对象,传递true
以获得一个数组。
代替:
$delete= json_decode($_POST['deleted']);
foreach($x as $delete){
echo "<script>alert(".$x.");</script>";
}
和:
$delete= json_decode($_POST['deleted'], true);
foreach($delete as $x){
echo "<script>alert(".$x.");</script>";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.