Frameworks used: JavaScript, AJAX, HTML. Cannot use JQuery
Have to display SQL table on page
Last column of the table should contain an image which acts like a delete button
On clicking that delete image, the row should be deleted from HTML table and SQL table
In my code the onClick is not working
HTML code
table rows displayed by looping through rows of sql query result.
<td>
<span class="delete" onClick="divFunction()" data-id="<?= $id; ?>"
><img src="delete.png"
/></span>
</td>
JavaScript code
document.addEventListener("DOMContentLoaded", function () {
function divFunction() {
// Storing element that will be deleted
var el = document.getElementById("delete");
var deleteid = el.getAttribute("data-id");
// Creating AJAX request
var params = "id=" + deleteid;
var request = new XMLHttpRequest();
request.open("POST", "remove.php", true);
request.setRequestHeader(
"Content-type",
"application/x-www-form-urlencoded"
);
request.send(params);
el.remove();
}
});
PHP Code
file name: remove.php
if (($con = mysqli_connect("localhost", "user", "password", "database", "port"))==false) {
die(mysqli_connect_error());
}
$id = 0;
if (isset($_POST['id'])) {
$id = mysqli_real_escape_string($con,$_POST['id']);
}
// Delete the row
$query = "DELETE FROM Coorporations WHERE id='".$id."'";
mysqli_query($con,$query);
mysqli_free_result($result);
mysqli_close($conn);
exit;