问题
I have this following code that delete a mysql record and I would like to transform it so It would be a ajax/jquery code so I can stay in the same page after the record has been deleted from the table. Now, it working fine but it not on the same page and I need to refresh the page to see the result. This is only a part of the full code. All the code in on one page.
//get the mysql results
//this is a repeated region
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['description']; ?></td>
<td><a href="manage.php?id=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
if ((isset($_GET['deleteid'])) && ($_GET['deleteid'] != "") && (isset($_POST['delete']))) {
$deleteSQL = sprintf("DELETE FROM my_table WHERE id=%s",
GetSQLValueString($_GET['deleteid'], "int"));
回答1:
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['description']; ?></td>
<td><div class="delete_class" id="<?php echo $row['id']; ?>">Delete</div></td>
</tr>
Now in the section write this
$(document).ready(function(){
$(".delete_class").click(function(){
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'delete_page.php',
data:'delete_id='+del_id,
success:function(data) {
if(data) { // DO SOMETHING
} else { // DO SOMETHING }
}
});
});
});
Now in the 'delete_page.php' page do this
$id = $_POST['delete_id'];
$query = "delete from TABLE NAME where ID = $id";
Rest I hope you know. Hope this helps
回答2:
Include jQuery and something like this will do the trick
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['description']; ?></td>
<td><a href="#" onClick="delete (<?php echo $row['id']; ?>); return false;">Delete</a>
</td>
</tr>
<script>
function delete(id){
$.post("manage.php", { deleteid: id , delete: true} );
}
</script>
来源:https://stackoverflow.com/questions/14106568/how-to-delete-a-mysql-record-with-jquery