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();
}
});
})
2
Answers
Okay, this is actually weird, I don't know how I fixed this issue or what was wrong, but that's what I basically did to make it work:
At first I was not getting the response from the php file at all (alert was empty), so I removed the
isset($_POST['remove'])
completely and commented out everything and just made the file toecho 'success'
. After that I was gettingalert:success
, then changedecho 'success'
to$title = $_POST['title']
and I was getting the response I needed. After that everything just started working. I'm not really sure what was the issue, but this works just fine now.delete.php
You don’t need the count. Just place the img_container outside of the while loop.
I did an example
HTML:
JQuery:
I did a example jsfiddle where you can play with the code:
https://jsfiddle.net/bogatyr77/qdeL4tcp/3/
Change this:
to
Here you have to put into your Url to the delete.php