1

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">&times;</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();
Prince Brucex
  • 499
  • 1
  • 5
  • 11
  • 1
    I bet @Danny Fardy, you did not read the OP. This error message `Notice: Undefined index: id in C:...delete.php` is not the main focus of the question. and Actually the PHP file is not the cause of my problem. I added the error message just as additional message. Please read the question well. The file was not suppossed to be opened. The file is not supposed to be opened. It will surely produce errors when oepened via browser but will work as expected it not opened. and actually it will never be opened when used in the production site – Prince Brucex Jan 22 '18 at 01:50

3 Answers3

2

I don't think you can use data attributes on option tag to open the modal. Instead you can open the modal using JavaScript.

After you select the delete option, you need to store the selected ID somewhere. In my demo, we store the ID in a variable.

$(function() {

  // we'll use this to hold current ID 
  var idToDelete;
  
  $('.all_options').on('change', function() {
    // check selected value (since you didn't specify value attribute to your options, it will use the text)
    if (this.value == 'Delete') {
      // store the ID to access it later e.g. variable or hidden input
      idToDelete = this.dataset.id;
      console.log('clicked Delete option: set idToDelete=' + idToDelete);

      // open modal
      $('#modal_box').modal('show');
    }
  });
  
  // no need to attach (and re-attach) click event handler inside the change event handler b/c the modal is already available in the DOM when the page loads
  $('#confirm-delete').click(function () {
    console.log('clicked Delete button: get idToDelete=' + idToDelete);
    // call AJAX 
  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<!-- ids are only supposed to appear once in the DOM, so use class if you have multiple of these -->

<!-- data attributes are useful to hold custom data -->
<select class="all_options" data-id="123">
    <option>Edit</option>
    <option>Delete</option>
</select>

<select class="all_options" data-id="456">
    <option>Edit</option>
    <option>Delete</option>
</select>

<select class="all_options" data-id="789">
    <option>Edit</option>
    <option>Delete</option>
</select>

<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">&times;</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>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
Mikey
  • 6,728
  • 4
  • 22
  • 45
  • 3
    @PrinceBrucex My demo does not use `id` as an attribute, it uses `data-id`. Each post would store its id in the `data-id` attribute. – Mikey Jan 22 '18 at 01:20
  • Thank you. I noticed I was wrong. I deleted my comment immediately but I think you had already seen it. I am putting your code to the test then I shall give feedback – Prince Brucex Jan 22 '18 at 01:53
  • thank you once again. I have tested your solution fully and it works great. The only issue is that my Ajax call evaluates to success even if no item is deleted. My ajax call is in the OP – Prince Brucex Jan 23 '18 at 03:30
  • @PrinceBrucex The success handler get called if your PHP script returns 200 status code, regardless if your query works or not. You need to (1) [check whether any rows were deleted](http://php.net/manual/en/mysqli.affected-rows.php) and (2) [send back the appropriate response and handle it](https://stackoverflow.com/a/14708366/1022914). If you want to send a non-200 status code, you need to [set the header](https://stackoverflow.com/questions/3258634/php-how-to-send-http-response-code). (BTW OP stands for Original Poster i.e. the person who ask the question i.e. you). – Mikey Jan 23 '18 at 03:49
  • I appreciate your assistance. Yeah and P in OP also stands for "Post", the Original thread that was started by the original poster – Prince Brucex Jan 23 '18 at 04:03
0

$('#all_options'). instead of $('.all_options').

  • thanks for the response, but `$('#all_options').` did not make difference. Also `$('#all_options').` is not recommended for use in my case because there are many posts on a single page having same `select` element and `options`. If i change the `attribute` to `id` instead of `class`, then several posts on the same page will have the same `id` which is not good practice – Prince Brucex Jan 22 '18 at 01:02
0

Try like this snipet:

$("#all_options").change(function(){
 var value = $(this).val();
  if(value=="delete"){
   $("#modal-id").modal("show")
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<select id="all_options">
    <option value="select">Select Option</option>
    <option value="delete" >Delete</option>
    <option value="edit" >Edit</option>
</select>
<div class="modal fade" id="modal-id">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h4 class="modal-title">Modal title</h4>
   </div>
   <div class="modal-body">
    
   </div>
   <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary">Save changes</button>
   </div>
  </div>
 </div>
</div>
Carlos Quintero
  • 268
  • 3
  • 14
  • I appreciate your response, but the your solution did not address the problem fully. I believe it would be more useful to other people if you had included some more details as to the specific part of the problem you are trying to solve – Prince Brucex Jan 23 '18 at 04:09