I need to delete data from Database via Ajax. When the user selects delete
option from html
select
element
, it must show bootstrap modal
. The user must then click on confirm delete
in order to start the deletion process. Although I get no error message at all from the JavaScript, I suspect the problem is from the JavaScript.
My html select options are as follows:
The id of the delete
and edit
options are also the id of the posts that must be deleted or edited.
NOTE: There are many posts on sample page and each post has this select
element
<select id="all_options">
<option id ="delete_option" data-toggle="modal" data-target="#modal_box" >Delete</option>
<option id = "edit_option">Edit</option>
</select>
The usual Bootstrap Modal box
is as follows with close
and delete
buttons.
When the delete option in the select element above is selected, the modal box will show
.
<div id= "modal_box" class="modal fade" role="dialog" style = "display:none;">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button id = "cancel_delete" type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button id = "confirm-delete" name = "confirm_delete" type="button" class="btn btn-primary">Delete</button>
</div>
</div>
</div>
</div>
Here is my JavaScript which is not working:
The JavaScript will collect the Id of the delete option in the select element above and send the id to the sever to identify the data that must be deleted from the database.
$(function(){
$('.all_options').on('change', function () {
var post_id = $(this).children(":selected").attr("id");
if(post_id){
//If delete button on the modal is clicked, start ajax deletion
$('#confirm_delete').click(function(){
$.ajax(
{
url: "delete.php",
type: "POST",
data: {
id: post_id
},
success: function (data) {
if(data){
alert("Successful!");
}else{
alert("Delete Failed");
}
}
});
});
}
});
The PHP file is like so:
$post_id = $_POST['id'];
$sql = "DELETE FROM test_ajax WHERE post_id = ?";
$stmt = $this->connect->prepare($sql);
$stmt->bind_param('s', $post_id);
$stmt->execute();