I have an HTML table that has 4 columns: SKU Group, Group_ID, Edit button, and Delete button. I am working on the delete function now and want it so that whenever I press the delete button, a confirmation box pops up and then if "OK" is pressed, it deletes the row and sends a delete query which deletes it from the database.
I know I am to use Ajax and a separate PHP script for the delete query, but cannot seem to figure it out. Any help is appreciated!
HTML for Delete Button:
<td><input type="button" class="delete" name="delete" value="Delete" onclick="deleteRow(this)"></td>
JavaScript...I know this needs some work but am posting it for the sake of my question:
function deleteRow(r) {
if (confirm('Are you sure you want to delete this entry?')) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("skuTable").deleteRow(i);
}
request = $.ajax({
type: "POST",
url: "delete.php",
data: i
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row deleted");
} else {
console.log("row failed to delete");
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
delete.php:
<?php
$SKU_Group = $_POST['SKU Group'];
$Group_ID = $_POST['Group_ID'];
$host="xxxxxx";
$dbName="xxxxxx";
$dbUser="xxxxxxxxxxxxxx";
$dbPass="xxxxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$delete = "DELETE FROM SKU_Group_Dim WHERE Group_ID = '$Group_ID'";
$stmt = $pdo->prepare($delete);
$result = $stmt->execute();
echo json_encode($result);
if(!$result) {
echo json_encode(sqlsrv_errors());
}
?>