I'm dynamically generating <div>
rows with 5 items per row using simple php while loop. Now my goal after that was to create a select form with dynamically created option
's as options to delete the selected item.
Now I think that the issue is, that my generated options don't interact with delete php file. I can delete the file manually using GET
and typing the required string into url, but it does not work after pressing the button using POST
.
Loop to create the rows:
<?php $count = 1;
while($data = mysqli_fetch_array($result)) {
if($count === 1) {
echo "<div class='img_container'>";
}
echo "<div class='img_div' id='".$data['title']."'>";
echo "<img src='uploads/" . $data['filename']."'>";
echo "<p delete_id='".$data['id']."' class='img_title' >" .$data['title']. "</p>";
echo "<p class='img_desc'>" .$data['photo_description']. "</p>";
echo "<p>" .$data['price']. "</p>";
echo "</div>";
if($count % 5 === 0) {
echo "</div>";
$count = 1;
continue;
}
$count++;
}
?>
Selection form:
<form class='flex-container' id='remove-form'>
<p>Select and Remove Item</p>
<select id='selectOpt' name='title'>
<option value="" selected disabled hidden>Choose Title</option>
</select>
<button id='rmvBtn' name='remove' <?php include_once 'delete.php' ?>>Delete</button>
</form>
Delete file:
if(isset($_POST['remove'])) {
$title = $_POST['title'];
$pdo = new PDO('mysql:host=localhost;dbname=project', 'root', '');
$query = 'DELETE FROM photos WHERE title = :title';
$stmt = $pdo->prepare($query);
$stmt->bindPARAM(':title', $title);
$stmt->execute();
}
jQuery to generate options and ajax:
(".img_title").parent().each((i,e)=> $("#selectOpt").append("<option value='" + e.id + "'>" + e.id + "</option>"));
//Delete selected item
$(document).on('click', '#rmvBtn', function() {
del_title = $("#"+ $("#selectOpt").val()).val();
$.ajax({
type: 'POST',
url: 'delete.php',
data: {title:del_title},
success: function() {
del_title.remove();
$("#selectOpt option:selected").remove();
}
});
})