I've been trying to delete rows from my handsontable (which is displaying rows from my database), but I can't find a solution to delete them using the "remove row" option. The plan is when I click on a row and remove the row, I want it to go into the delete_com.php and delete this row from the database. This should be done by getting the ID on the row you're removing on the handsontable and then using the ID it should remove it from the database.
I've tried using ajax and passing the ID in the table into another file to delete in the database, but nothing is getting deleted.
function deleteRowsFromDatabase(rowToDelete) {
var idToDelete = rowToDelete[0];
$.ajax({
type: 'POST',
url: 'delete_com.php',
data: { ids: [idToDelete] },
success: function(response) {
console.log('Rows deleted successfully:', response);
if (response.length > 0 && response[0].ID) {
var deletedID = response[0].ID;
var rowIndex = hot.getData().findIndex(function(row) {
return row[0] === deletedID;
});
if (rowIndex !== -1) {
hot.alter('remove_row', rowIndex);
}
}
},
error: function(xhr, status, error) {
console.error('Error deleting rows:', error);
}
});
var rowIndex = hot.getSourceData().indexOf(rowToDelete);
if (rowIndex !== -1) {
hot.alter('remove_row', rowIndex);
}
}
hot.addHook('afterRemoveRow', function(index, amount) {
var removedRows = loadedData.slice(index, index + amount);
console.log('ammount', amount, 'index', index)
deleteRowsFromDatabase(removedRows);
});
EDIT:
I've found out that if i delete a row that has another row below it, it'll send this data through but it sends the row below the removed row instead.
For example: I deleted a row with the ID: 5. It'll remove this from the table (temporarily) and in the console log it shows it's trying to remove the row with ID: 6.
SOLVED INDEX ROW PROBLEM:
hot.addHook('beforeRemoveRow', function (index, amount) {
var removedRows = loadedData.slice(index, index + amount);
console.log('amount', amount, 'index', index);
hot.addHookOnce('afterRemoveRow', function () {
deleteRowsFromDatabase(removedRows);
});
});
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['ids'])) {
$ids = $_POST['ids'];
$idList = implode("','", $ids);
$stmt = $conn->prepare("DELETE FROM com WHERE ID IN ('$idList') AND company = ?");
$stmt->bind_param("i", $compid);
$stmt->execute();
$stmt->close();
echo "Rows deleted successfully", $idList;
} else {
echo "No IDs sent";
}
}
This the PHP code inside of the delete_com.php. It should be deleting the row with the ID that's been selected, but it just passes through this code and says "Rows deleted succesfullyArray" in the console, but it hasn't.