使用ajax和jquery

时间:2018-03-05 12:32:01

标签: php jquery ajax

您好我有一个product_detail.php页面。在此页面描述有关产品和编辑和删除按钮。我想删除点击删除按钮上的产品。我收到提示消息您确定要删除此产品吗?但没有任何效果。这是我的product_detail.php页面代码如下:

<div class="col-sm-12">
    <h4><strong>Description:</strong></h4><hr>
    <p class="text-justify"><?php echo $row['description'];?></p>

    <form id="product_detail">
        <button class="btn product_publish" type="button">Publish Live</button>
        <button class="btn btn-edit" name="btn-edit">Edit</button>
        <button class="btn product_delete" type="button" id='del_<?php echo $id; ?>'>Delete</button>
    </form>                                                 
</div>

这是我的validation.js页面代码:

$('.product_delete').click(function(){
var el = this;
var id = this.id;
var splitid = id.split("_");
// Delete id
var deleteid = splitid[1];

if (confirm("Are you sure you want to delete this product?")){          
    $.ajax({
    url:'includes/backend_product_detail.php',
    type: "POST",
    data: { id:deleteid },      
    success:function(answer_from_actionpage){
    if(answer_from_actionpage == 1){
        window.location.href="product.php";
        //$('.form-control').val("");
    }else{
        $('.error').html(answer_from_actionpage);
    }
}
})
}
});

这是我的backend_product_detail.php页面代码:

<?php   
    include("dbconfig.php");

    $id=$_POST['id'];       
        $sql="DELETE FROM product WHERE id='$id'";
        if (mysqli_query($conn, $sql)){
            echo 1;
        }       
?>

如何删除特定产品记录。

1 个答案:

答案 0 :(得分:0)

在jquery代码中尝试这样的事情:

$.ajax({
  method: "POST",
  url: "includes/backend_product_detail.php",
  data: { id: deleteid }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });

并且还要确保在PHP脚本中阻止SQL Injection并首先使用以下if语句检查$id

// ...
if (is_numeric($id)){
    $sql="DELETE FROM product WHERE id=" . $id;
    if (mysqli_query($conn, $sql)){
        echo 1;
    }   
}