Search code examples
javascriptajaxconfirm

jQuery's $.ajax method does not work with JavaScript confirm() method


I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.

The application has a delete post functionality. I got stuck at deleting posts via jQuery's $.ajax method.

The posts view looks like this:

<table class="table table-striped table-sm border-0">
  <thead>
    <tr>
      <th>#</th>
      <th class="w-50">Title</th>
      <th>Publication date</th>
      <th class="text-center">Actions</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($posts as $index => $post): ?>
    <tr id="<?php echo $post->id; ?>">
      <td class="text-right"><?php $count = $index + 1; echo $count + $offset; ?></td>
      <td><?php echo $post->title; ?></td>
      <td><?php echo nice_date($post->created_at, 'D, M d, Y'); ?></td>
      <td class="text-center">
        <div class="btn-group btn-group-sm" role="group">
          <a href="<?php echo base_url('posts/post/') . $post->id; ?>" class="btn btn-success"><i class="fa fa-eye"></i> View</a>
          <?php if($this->session->userdata('is_logged_in') && $this->session->userdata('user_id') == $post->author_id) : ?>
          <a href="<?php echo base_url('posts/edit/') . $post->id; ?>" class="btn btn-success"><i class="fa fa-pencil-square-o"></i> Edit</a>
          <a href="#" id="delete_post" data-id="<?php echo $post->id ?>" class="ajax-btn btn btn-success"><i class="fa fa-trash"></i> Delete</a>
          <?php else: ?>
          <a href="#" class="btn btn-success disabled"><i class="fa fa-pencil-square-o"></i> Edit</a>
          <a href="#" id="delete_post" class="btn btn-success disabled"><i class="fa fa-trash"></i> Delete</a>
          <?php endif; ?>
        </div>
      </td>
    </tr>
    <?php endforeach ?>
  </tbody>
</table>

The jQuery meant for delateing posts via $.ajax:

//Delete Posts
$('#delete_post').on('click', function(evt){
    evt.preventDefault();
    var deleteUrl = $(this).attr('href');
    var id = $(this).data('id');

    if(confirm('Delete this post?')) {
      if ($(this).hasClass("ajax-btn")) {
        $.ajax({
          url: 'posts/delete/' + id,
          method: 'GET',
          dataType: 'html',
          success: function(deleteMsg){
            $('tr#' + id).fadeOut('250');
            $('#delete_msg').html('<p>Post successfully deleted</p>');
            $('#delete_msg').slideDown(250).delay(2500).slideUp(250);
          }
        });
      } else {
        window.location.href = deleteUrl;
      }
    }

});

The code above does not work for some reason. Where am I wrong?


Solution

  • You can't have the same id on multiple elements. Instead, give your delete button a class:

    <a href="#" id="delete_post" data-id="<?php echo $post->id ?>" class="delete-post ajax-btn btn btn-success">
    

    ...and then use .delete_post instead of #delete_post:

    $('.delete_post').on('click', function(evt){