M
M
Mark2020-04-24 16:47:09
JavaScript
Mark, 2020-04-24 16:47:09

How to remove a specific element via ajax?

Good day everyone.
I have a form on one page that, upon submitting a post-request in php, writes data to the database, and then using ajax updates the table, introducing new data into it, obtained as a result of executing php code.
The update occurs in the table only inside the tag
AND the structure looks like this:

<tr>
  <input type="hidden" name="form_id" value="<?=htmlspecialchars($users['id'], ENT_QUOTES)?>">
  <td><?=htmlspecialchars($users['item_name'], ENT_QUOTES)?></td>
  <td><?=htmlspecialchars(round($users['quantity'], 2), ENT_QUOTES)?></td>
  <td><button type="button" name="delete_item" id="item_delete" class="delete_btn"</button></td>
</tr>

Here is the actual code that removes one of the rows, selecting it by id:
$('button[id="item_delete"]').on('click', function() {
    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").html(html);
              $('#order')[0].reset();
          }
        });
        return false;
    });

The thing is that after a normal page load or after an update, everything works correctly - one id is passed and the specific line in which the button was pressed is deleted.
And if I entered the data into the form and updated the table with ajax, then in php, at the click of a button, all id from the form are transferred at once and only the most recent one is deleted, respectively.
A piece of php code that displays a table after all database manipulations are completed:
$message = '<tr>';
foreach ($user as $users) {
  $message .= ' <input type="hidden" name="form_id" value="' . $users['id'] . '">
  <td>' . $users['item_name'] . '</td>
  <td>' . $users['quantity'] . '</td>
  <td><button type="submit" name="delete_item" id="item_delete" class="delete_btn" value="' . $users['id'] . '" ></button></td>
  </tr>';
  }
echo $message;

I understand that I missed something somewhere, but I do not understand what exactly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
ThunderCat, 2020-04-24
@yourbatya

At the time of page loading, a listener was hung on the buttons, dynamically added elements, respectively, do not have such a listener, and will not work. Hang a listener on the document and track the target, in the LCD like this:

$(document).on('click', 'button[id="item_delete"]',function() {...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question