I’m trying to remove content with jQuery/ajax which is dynamically added with a simple PHP loop, but it does not work.
I’m using dynamically created <select>
option
to select the item and remove it by pressing the button
. This is what I came up until now:
jQuery:
$(document).on('click', '#rmvBtn', function() {
// remove the related element
let del_title = $("#" + $("#selectOpt").val());
$.ajax({
type: 'POST',
cache: false,
processData: false,
url: 'delete.php',
data: {title:del_title},
success: function(data) {
if(data) {
del_title.remove();
}
}
});
})
PHP delete:
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_NAME", "project");
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if($mysqli->connect_error) {
echo "Sorry, there's a problem with the website.n";
echo 'Error: ' . $mysqli->connect_error . 'n';
exit();
}
if($_POST['title']) {
$title = mysqli_real_escape_string($_POST['title']);
$sql = "DELETE FROM photos WHERE title = $title";
mysqli_query($sql);
}
HTML Form to remove Item:
<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> /*default value*/
/*here appear the dynamically created options*/
</select>
<button id='rmvBtn'>Delete</button>
</form>
2
Answers
I created this little example.
I’ve edited your code and add
echo
to send success/failed message back to Ajax as debugging purposes. I’ve changeddata: {title:del_title}
todata: {title:del_title.val()}
. I’ve also noticed syntax error in yourphp
code:if($_POST['title']) { })
. There shouldn’t be a)
at the end of if statement.jQuery:
PHP delete:
html form to remove the items:
I’d also recommend handling MySQL Errors when using Ajax, refer to this answer.