I am very new to web programming in general and I have some issues in creating a simple client database. I have to find a way to delete clients from the database using Ajax. I try to find a solution without using jQuery... So far I managed to set up a script and php code to delete one database entry; However it is not possible to delete another client without refreshing the page first. Could someone help me find out what to do to solve this problem?
Relevant parts from my index.php
<?php
require_once "CRM_DB.php";
$clients = CRM_DB::showAll();
?>
...
<div class="container">
<div class="row mb-4">
<div class="col-sm-12">
<h2>All Entries</h2>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>E-Mail</th>
<th>Comment</th>
<th>Created At</th>
<th>Updated At</th>
<th>Delete</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<? foreach($clients as $client): ?>
<tr id="table-row">
<td><?= $client->id ?></td>
<td><?= $client->name ?></td>
<td><?= $client->email ?></td>
<td><?= $client->text ?></td>
<td><?= $client->created_at ?></td>
<td><?= $client->updated_at ?></td>
<td>
<form action="" class="delete-form m-0" method="post">
<input type="hidden" id="del-id" name="id" value="<?= $client->id ?>">
<input type="hidden" name="delete" id="delete" value="1">
<button type="submit" class="btn btn-danger btn-sm" id="delete_btn" onclick="deleteID(); return false">Delete</button>
</form>
</tr>
<? endforeach; ?>
</tbody>
</table>
....
<script type="text/javascript">
function deleteID() {
var id = document.getElementById('del-id').value;
var del = document.getElementById('delete').value;
var params = 'delete='+encodeURIComponent(del)+'&id='+encodeURIComponent(id);
var url = 'crm.php';
xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
if(this.readyState == 4 && this.status == 200) {
document.getElementById('table-row').innerHTML = this.response;
}
};
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(params);
}
</script>
crm.php
if(isset($_POST["delete"]) && isset($_POST["id"])) {
$id = $_POST["id"];
CRM_DB::deleteClient($id);
}
CRM_DB.php
public static function deleteClient($id) {
$db = self::db();
$query = "DELETE FROM clients WHERE id = ?";
$result = $db->query($query, [$id]);
return $result;
}
public static function showAll() {
$db = self::db();
$query = "SELECT * FROM clients";
$result = $db->query($query);
$clientArray = [];
for($i = 0; $i < $result->num_rows; $i++) {
$row = $result->fetch_array();
$client = self::convertToObject($row);
$clientArray[] = $client;
}
return $clientArray;
}
public static function convertToObject($row) {
return new Client($row["id"], $row["name"], $row["email"], $row["text"], $row["created_at"], $row["updated_at"]);
}
}
parent / sibling selectorsto find the correct form elements rather than trying ( and failing ) to use ID attributes which must be unique