Klapsius Klapsius - 1 month ago 9
Ajax Question

delete record via AJAX when table are generated with JQuery append

I have a html table with data. And i would like to delete records via

ajax
but i struggling little bit because my table are generated with
append
:

...
$.each(data, function(id, won) {
if (data[i].flag == 0) {flag='<img src="../images/flag-y.png" width="20" height="20">'} else {flag='<img src="../images/flag.png" width="20" height="20">'}

$el.append('<tr><td>'+data[i].id+'</td>
<td><a href="?identifier='+data[i].id+'&token='+data[i].token+'"><img src="../images/edit.png" width="20" height="20"></a></td>
<td><a href="?delete='+data[i].id+'&deletetoken='+data[i].token+'"><img src="../images/delete.png" width="20" height="20" class="delete"></td> </tr>');
i = ++ i;
} );
...


It works. but how to pass parameter into ajax call if somebody clicks the picture on to last column (i don't need a help with php file)?

$('a.delete').click(function(e) {
e.preventDefault();

var parent = $(this).parent();
$.ajax({
type: 'get',
url: 'jquery-record-delete.php',
data: 'ajax=?delete,
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});

});


I need to pass delete and deletetoken variables.

Answer

I suggest you add data-id attribute to each <tr>, like this:

$el.append('<tr data-id="+ data[i].id +">
    + '<td>' + data[i].id + '</td>'
    + '<td>'
        + '<a href="?identifier=' + data[i].id + '&token=' + data[i].token + '">'
            + '<img src="../images/edit.png"  width="20" height="20">'
        + '</a>'
    + '</td>'
    + '<td>'
        + '<a href="?delete=' + data[i].id + '&deletetoken=' + data[i].token + '" class="delete">' // also, you listen to a.delete click, so let's add "delete" class to it
        + '<img src="../images/delete.png" width="20" height="20" class="delete">'
        + '</a>' // I think you were missing closing a tag here
    + '</td>'
+ '</tr>');
i++;

So you can grab it easily in the listener callback:

$('body').on('click', 'a.delete', function(e) {
    e.preventDefault();

    var tr = $(this).closest('tr'),
        id = tr.data('id'); // we have the ID
    $.ajax({
        type: 'get',
        url: 'jquery-record-delete.php',
        data: {
            id: id, // passing id
            ajax: 'delete'
        },
        beforeSend: function() {
            tr.animate({'backgroundColor':'#fb6c6c'},300);
        },
        success: function() {
            tr.slideUp(300,function() {
                tr.remove();
            });
        }
    });
});