通过AJAX请求删除

时间:2017-10-20 15:58:33

标签: php ajax

我有一个按钮,可以调用此AJAX请求来删除记录。 我怎样才能正确显示/处理mysql错误,如:

  

错误:表'supplier_contacts'不存在

// DELETE
$('.delete-btn').click(function () {

  // Confirm
  if (!confirm('Are you sure want to delete this row?')) {
    return false;
  }

  // id need to delete
  var contact_id = $(this).attr('contact_id');

  // Current button 
  var obj = this;

  // Delete by ajax request
  $.ajax({
    type: "post",
    dataType: "text",
    url: 'suppliers_sql.inc.php?a=delete_contact',
    data: {
      contact_id: contact_id
    },
    success: function (result) {
      $(obj).parent().parent().remove();
      window.location.assign('suppliers_details.php?id=<? echo $supplier_id ?>&m=success');
    }
  });

});


SQL QUERY of suppliers_sql.inc.php ? a = delete_contact

// --------------------------------------------------------------------------------------------
// DELETE CONTACT
// --------------------------------------------------------------------------------------------     
if ($_REQUEST['a'] == "delete_contact") {

  $contact_id = $_POST['contact_id'];

  $sql_contact = "DELETE FROM supplier_contacts WHERE contact_id = $contact_id";

  if (mysqli_query($mysqli, $sql_contact)) {
    mysqli_close($mysqli);
    //header("Location: suppliers_details.php?id=$supplier_id&m=success");
    exit;
  } else {
    echo "Error: " .$sql_contact. "<br>" .mysqli_error($mysqli);
    mysqli_close($mysqli);
    exit;
  }

}

1 个答案:

答案 0 :(得分:0)

如果您发现错误,可以回复某些内容,您可以在成功时显示错误。

   $.ajax({
   type : "post",
   dataType : "text",
   url : 'suppliers_sql.inc.php?a=delete_contact',
   data : {
      contact_id : contact_id
      },
      success : function(result){
         if(result)
         {
            //Your error
            alert(result);
         }
         else
         {
            //all good
            $(obj).parent().parent().remove();
            window.location.assign('suppliers_details.php?id=<? echo $supplier_id ?>&m=success');
         }
      }                       
   });