Home » Php » javascript – Delete a table row with dynamic id that comes from DB using ajax

javascript – Delete a table row with dynamic id that comes from DB using ajax

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a table that it’s content is comes from database.When I click on the delete button I want to delete that row with Ajax. Actually right now it’s working but with a bug and that is all of the rows get deleted when I click on the button and then if I refresh , the row that I was deleted is gone and other rows are shown.But as I said it needs a refresh.Any solution would be appreciated .

$('.dashboard-subscribe-form').submit(() => {
  event.preventDefault();
  const currentHiddBtn = $('.dash-subscribe-form-btn');
  console.log(currentHiddBtn.closest('tr'));

  const userCaution = confirm('Want to delete this quote?');
  if (userCaution) { //If admin insists to delete the row
    const deleteId = $('.dash-subscribe-form-btn').attr('value');
    $.ajax({
      type: "POST",
      url: "delete-subscribe.php",
      dataType: "json",
      data: {
        deleteId: deleteId
      }, 
      success: (data) => {
        if (data.code === '200') {
          console.log('It works!');
          currentHiddBtn.closest('tr').css('background', 'tomato');
          currentHiddBtn.closest('tr').fadeOut(1200, () => {

          });

        } else if (data.code === '404') {
          alert('An error occurred!Please try again.');
        }
      }
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tbody>
  <?php
       $count = 1;
       $sqlCommand = "SELECT * FROM `kq0b3_subscribe`";
       $sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
       $sqlCommandPrepare->execute();
       while ($result = $sqlCommandPrepare->fetch()) {
   ?>
   <tr id="row-<?php echo $result['id']; ?>">
      <td class="dashboard-records">
        <?php echo $count; ?>
      </td>
      <td class="dashboard-records">
        <?php echo $result['email']; ?>
      </td>
      <td>
        <form action="" method="post" class="dashboard-subscribe-form">
          <input id="<?php echo $result['id']; ?>" type="hidden" class="dash-subscribe-form-btn" name="hidden-del" value='<?php echo $result[' id ']; ?>'/>
          <button type="submit" name="sub-del-btn" class="btn btn-danger del" value='<?php echo $result[' id ']; ?>'> Delete
           </button>
        </form>
      </td>
    </tr>
    <?php
     $count++;
       }
     ?>
</tbody>

delete-subscribe.php:

<?php
require_once('config.php');

$delete_row = $_POST['deleteId'];


if($delete_row){
    $sqlCommand = "DELETE FROM `kq0b3_subscribe` WHERE `id` = ?";
    $sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
    $result = $sqlCommandPrepare->execute([

        $delete_row

    ]);

    /*The json_encode() must be after all of our calculation codes and DB query codes and...(It must be the
       last line of code) */
    echo json_encode(['code' => '200'], JSON_THROW_ON_ERROR, 512);
}
else {
    echo json_encode(['code' => '404'], JSON_THROW_ON_ERROR, 512);
}

UPDATE2: now I’m using :

 $('#row-' + deleteId).css('background', 'tomato');
                    $('#row-' + deleteId).fadeOut(1200, () => {

                    });

but the new problem is : it doesn’t matter which button I click, the forst row is deleted (when any button is clicked , in the console , the id of the first row-button is printed , not the actual id that I was clicked. ).How can I fix this one?

How to&Answers:

I think the main issue, in this case, is using CSS classes as a selector and it seems to be selecting the first instance no matter which item you are clicking.

The code causing this is:

const deleteId = $('.dash-subscribe-form-btn').attr('value');

You want to be getting the target input from the event object passed from your .submit().

I have created a jsfiddle with an example that could be adapted to your code but here is a quick preview of jQuery part.

$('.dashboard-subscribe-form').submit((event) => {
  event.preventDefault()
  console.log(event.target.elements[0]["value"])
  $('#result-from-click').html("Input Value: " + event.target.elements[0]["value"])
})

It is selecting the first element within the elements array which is the input. If you want the button you can use event.target.elements[1]

You could then also use the value returned to remove the <tr> with the same id instead of finding the nearest. This could be done in the success part of your ajax call without doing a refresh.