M
M
Maxim2020-05-01 17:36:58
PHP
Maxim, 2020-05-01 17:36:58

How to remove elements loaded dynamically?

Good afternoon.
I have a list on a page that is loaded using ajax and the problem is that I cannot remove elements from it that are loaded dynamically, i.e. when reloading the page, everything works correctly, but when loaded via ajax - no.

<tbody id="table_ajax">
<?php foreach ($post as $vars): ?>
<tr>
   <input type="hidden" name="form_id" class="id_inp" value="<?=htmlspecialchars($vars['id'], ENT_QUOTES)?>">
   <td><?=htmlspecialchars($vars['item_name'], ENT_QUOTES)?></th>
   <td><?=htmlspecialchars($vars['item_qty'], ENT_QUOTES)?></td>
   <td><button type="button" name="delete_item" id="item_delete" class="close deleter">delete</button></td>
</tr>

$(document).on('click', 'button[class="close deleter"]', function() {
  event.preventDefault();
  let $row = $(this).closest('tr');
  let data = $row.find('input').serialize();
  $.ajax({
    type: "POST",
    url: "delete_me.php",
    data: data,
    success: function(html){
      $("#table_ajax").load('table.php');
      $('#order')[0].reset();
    }
  });
  return false;
});

If I understand correctly, then when loading the table via ajax, I don't have a listener on the elements. I added a document to the script, but it still only fires when the page is refreshed.
Tell me, please, what could be the matter and in which direction to look?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2020-05-06
@ikfah012

The correct option was this, I just made a mistake when outputting - in table.php I displayed a hidden input outside the tr, that's why it didn't work.

poke
$(document).on('click', 'button[name="delete_item"]', function() {
  event.preventDefault();
    let $row = $(this).closest('tr');
    let data = $row.find('input').serialize();
    $.ajax({
            type: "POST",
            url: "delete_item.php",
            data: data,
            success: function(html){
              $("#table_ajax").load('table.php');
              $('#order')[0].reset();
          }
        });
        return false;
    });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question