简体   繁体   中英

Record not deleting using php/ajax

If I console.log the ID out after I am meant to delete the record, the correct ID displays in console. So, it seems that it is connected up properly but doesn't actually delete a record from my database. I cannot figure this out but it's probably something obvious.

JS

<script type="text/javascript">
$(document).ready(function() {
    $('.table-row').on('click', function (e) {
        e.preventDefault();
        var $otId = $(this).data('ot-id');
        swal({
            title: 'Are you sure?',
            text: "You won't be able to undo this!",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#FB404B',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!',
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                $.ajax({
                    type: 'post',
                    url: 'functions/delete-ot-request.php',
                    data: {otId: $otId},
                    success: function (result) {
                        // window.location.href = 'delete-ot.php'; 
                        console.log($otId);
                    },
                });
            } else {
                swal("Cancelled", "Maybe next time then.", "error");
            }
        });
    });
});
</script>

PHP

if(isset($_POST['otId'])) {
    $stmt = $link->prepare("DELETE FROM `ot_request` WHERE `id` = ? LIMIT 1");
    $stmt->bind_param("i", $_POST['otId']);
    $stmt->execute();
    $stmt->close();
} 

This is the html table row that holds the id:

<tr class="table-row" data-ot-id="{$id}"></tr>

Your console.log($otId); reports the id value you previously sent , not a data coming back from the server side.

Hence this output attests only that the ajax process was successful, not the server job, which is likely what turns wrong for some reason.

So you should look for errors at the server side, starting with sending back some execution trace:

if(isset($_POST['otId'])) {
  try {
    $stmt = $link->prepare("DELETE FROM `ot_request` WHERE `id` = ? LIMIT 1");
    $stmt->bind_param("i", $_POST['otId']);
    $stmt->execute();
    $stmt->close();
    echo 'otId "' . $_POST['otId'] . '" processed';
  } catch(PDOException $e) {
    echo $e->getMessage;
  }
} else {
  echo 'No otId found';
}

And modifying your Javascript so you output this trace:

success: function (result) {
  console.log(result);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM