I have a problem, a dynamically updated table is not working. When I manually refresh the page, it works correctly, I can delete the record. As soon as I add a user to the table, the table is dynamically updated via the database, but then I cannot delete the records. It feels like there is no table on this page.

// AJAX - dynamically update the table. function dynamicTable() { $.ajax({ type: 'GET', url: 'table.php', dataType: "html", success: function( html ){ console.log(html); $("#trash").html(html); } }); } //AJAX - delete record $('#trash td').on('click', function(e) { console.log(111) // e.preventDefault(); // if you do NOT click on the picture -> exit if (e.target.nodeName != 'IMG') { return false; } else { let id = $(this).data('label'); $(this).parent('tr').remove(); // get the text from the `ID U` for deletion by id var parentDel = this.parentElement.children[1].textContent; } $.ajax({ type: 'POST', url: 'regist.php', data: { id_delete: parentDel, }, success: function( response ){ dynamicTable(); console.log(response); } }); }); 

 $query = 'SELECT phones_users.id, phones_users.id_user, users.user_first_name, users.user_last_name, phones_users.phone_1, phones_users.phone_2 FROM users INNER JOIN phones_users ON users.id = phones_users.id_user'; $result = mysqli_query($con, $query); $count_users = mysqli_num_rows($result); if ($count_users) { while ($row = mysqli_fetch_array($result)) { echo "<tr><td data-label='ID R'>$row[0]</td><td data-label='ID U'>$row[1]</td><td data-label='Name'>$row[2]</td><td data-label='Last Name'>$row[3]</td><td data-label='Phone 1'>$row[4]</td> <td data-label='Phone 2'>$row[5]</td> <span><td style='padding: 5px;'> <a href='#'> <img src='img/trash.png' width='25px' height='25px'> </a> </td></span> </tr> "; } // var_dump($query); } ?> 

    1 answer 1

     $('#trash').on('click', 'td', function(e) { ... 

    Explanation

     $('#trash td').on('click', function(e) { 

    '#trash td' click event handler only to the '#trash td' selection elements that exist when this line of code is executed. The td elements inside #trash that appear later will not be affected by this handler.

     $('#trash').on('click', 'td', function(e) { 

    attaches a handle to the '#trash' element, and this handler will be called if the event occurred on the td element. Thus, all that is needed at the moment of executing this code is the existence of the '#trash' element. The handler will be called for the 'td' elements, both existing and later created.

    • Thank you, helped, and can you explain what the puncture is? What is the difference? - Misha Podlevsky