I am trying to delete data using checkboxes and the result is either nothing happens or Attempt to read property "id" on null Is it because the table is in a function, should I be placing checkbox input in the html file? and I am not quite sure how to connect the checkbox[] part with the requests. I am out of ideas…
button tag <button class="mass-btn" id="deleteBtn" > MASS DELETE</button>
The delete function..
$query = 'DELETE FROM ' . $this->table . 'WHERE id = :id';
$stmt = $this->conn->prepare($query);
$this->id = htmlspecialchars(strip_tags($this->id));
$stmt->bindParam(':id', $this->id);
$stmt->execute();
the delete.php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: DELETE');
include_once '../../config/database.php';
include_once '../../models/post.php';
//Instantiate db
$database = new Database();
$db = $database->connect();
//Instantiate post
$product = new Post($db);
//Get raw data
$data = json_decode(file_get_contents("php://input"));
$product->id = $data->id;
if($product->delete()) {
echo json_encode(
array('message' => 'Product Deleted')
);
} else {
echo json_encode(
array('message' => 'Product Not Deleted')
);
}
the table with input…
async function renderUser() {
let users = await getUsers();
let html = ``;
users.forEach(user => {
let htmlSegment = `
<table class="box">
<tr>
<th> <input type='checkbox' id='checkbox' name='checkbox[]'> </th>
<td> ${user.sku}</td>
<td> ${user.name}</td>
<td> ${user.price}</td>
${user.size ? `<td> Size: ${user.size} $ </td>` : ""}
${user.weight ? `<td> Weight: ${user.weight} Kg</td>` : "" }
${user.height ? `<td> Height: ${user.height} CM</td>` : ""}
${user.length ? `<td> Length: ${user.length} CM</td>` : ""}
${user.width ? `<td> Width: ${user.width} CM</td>` : ""}
</tr>
</table>`;
html += htmlSegment;
});
let container = document.querySelector('.message');
container.innerHTML = html;
}
renderUser();
};
the XMLRequest and Fetch API attempt
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('deleteBtn').onclick=function(){
var req;
req=new XMLHttpRequest();
req.open('DELETE', '/api/post/delete.php');
req.send();
req.onload=function(){
if (req.readyState === 4 && req.status == "204") {
console.table(json);
} else {
console.error(json);
}
req.send(null);
};
};
});
let btnDel = document.getElementById('#deleteBtn');
let deleteData = async () => {
let response = await fetch ('../api/post/delete.php', {
method: 'DELETE',
headers: {'Content-Type': 'application/json' },
body: JSON.stringify(id)
})
try {
let res = await fetch(url);
return await res.json();
} catch(error) {
console.log(error);
}
}
btnDel.addEventListener('click', deleteData);