Edit:
As per solution provided in the comments below.
The nothing happening in the Database
The solution was a simple refresh of the page as I previously had the delete.php file in a different directory (so the code worked fine... it was just a case of mistaken identity - it's always the littlest things).
The nothing happening on the page
The solution was giving the parent <div> a unique id (the same as the delete-button/image - 1) and then under the ajax-function in my jQuery.js file adding...
success: function() {
$('#'.concat(id)).remove();
}
Thank you to @SikanderNawaz
End Edit
I'm trying to delete a row in my Database by using jQuery, AJAX and PHP, and my code, should be, but is not working.
I click the delete-button, but nothing happens, on the page or in the Database.
Where did I go wrong?
Hope someone here can help.
Database
------------------
| id | link |
------------------
| 1 | image.jpg |
------------------
HTML
<head>
...
<script src="jquery-3.4.1.js"></script>
...
</head>
<body>
...
<button type="button" name="delete" id="delete" class="some stylings" value="1"><h6><b>X</b></h6></button>
<img src="images/image.jpg" />
...
<script src="jQuery.js"></script>
</body>
jQuery.js
$(document).ready(function(){
$('button#delete').click(function(){
var id = $(this).val(); // tested and returns 1 (see button value)
$.ajax({
url: 'delete.php',
type: 'post',
data: { id: id },
success: function() {
$('#'.concat(id)).remove();
}
});
});
})
delete.php
<?php
require ("connection.php");
if (isset($_POST['id'])) {
$id = $_POST['id'];
try {
$sql =
"
DELETE FROM test
WHERE
id = ?
";
$prepareTest = $pdo->prepare($sql);
$prepareTest->execute([$id]);
} catch(PDOException $e) {
file_put_contents('../error/e.txt', $e->getMessage(), FILE_APPEND);
}
}