3

I perform an ajax call that stores some data and adds a row in a table. In this row there is a delete button at the end so you are able to instantly delete the row you created if you want.

For some reason when I click the delete button I get redirected to the deleteurl of the ajax call I use to delete the data from the database. When I reload the page and press the delete button it works fine.

Anyone knows why this is happening?

The row that is being added:

<tr>
    <td>test</td>
    <td>
        <form class="deleteBuildingForm" method="POST" action="http://127.0.0.1:8000/buildingimage/42" accept-charset="UTF-8">
            <input name="_method" type="hidden" value="DELETE">
            <input name="_token" type="hidden" value="EEV90wmDNLMd8hg9ilh6zdDAjVShXW9bfOCXdvml">
            <button type="submit" class="btn btn-danger">
                <i class="far fa-trash-alt"></i>
            </button>
        </form>
    </td>
</tr>

My jquery code:

$('.deleteBuildingForm').on('submit', function(e) {
    e.preventDefault();

    axios.delete($(this).attr('action'), []).then(response => {
        $(this).closest('tr').remove();

        $('.successMessages').hide();
    });
});
Michael
  • 556
  • 1
  • 8
  • 27
  • Maybe `return false;` would help ? – Kuba Feb 04 '19 at 15:21
  • @Kuba what do you mean? – Michael Feb 04 '19 at 15:22
  • Instead of `e.preventDefault();` add at the end of submit callback `return false;` – Kuba Feb 04 '19 at 15:23
  • @Kuba I tried it, same issue – Michael Feb 04 '19 at 15:24
  • You're adding the button dynamically. You need to write something like $('body').on('submit', '.deleteBuildingForm', function (... The events are created when page loads, if you add the item after, the event won't trigger because it doesn't know what elements its referring to. By refreshing, it finds the element and it works. By changing the code to what I wrote, it checks for events on the body instead of an unexisting element – anthomaxcool Feb 04 '19 at 15:24

1 Answers1

5

I think the problem is that your new rows do not have the event handlers bound to them because they were dynamically created.

Event binding on dynamically created elements?

Try adding the event handler to the document, which will always exist.

$(document).on('submit','.deleteBuildingForm' ,function(e) {
    e.preventDefault();

    axios.delete($(this).attr('action'), []).then(response => {
        $(this).closest('tr').remove();

        $('.successMessages').hide();
    });
});
bassxzero
  • 4,838
  • 22
  • 34