Jonathan Jonathan - 1 month ago 5
jQuery Question

display records with ajax/jquery/json and delete

I am displaying records from the database like this:

$(document).ready(function(){
$.ajax({
url: 'functions/list-articles-delete.php',
dataType: 'json',
method: 'POST',
success: function(data) {
$.each(data, function(item){
var tr_str = "<tr>"
+ "<td>" + data[item].n_title + "</td>"
+ "<td>" + data[item].n_dateTime + "</td>"
+ "<td><button class='btn btn-danger' id='deletebut' data-id='" + data[item].id + "'>Delete</button></td>";
$( "#output" ).append(tr_str);

$( "#deletebut" ).on('click', function(){
// display id of associated record
});
});
},
});
});


When I click on any of the buttons I want it to console.log() the id of the associated record but not quite sure how to do this?

Answer Source

You are currently giving all the buttons the same id. In HTML, all id's must be unique.

We can actually remove the id's and just use a class instead. That way, we can register one event that covers all the buttons at the same time.

Here's how I would to this:
(Read the comments for an explanation of the changes)

// First, register an event on all the buttons that exists, and 
// might be added, that has the class delete-btn.
// Put this code directly in your document.ready.

$("body").on('click', ".delete-btn", function() {
    // Get the data-id value from the button
    console.log($(this).data('id')); 
}

Now, change your loop:

$.each(data, function(index, item) { // The second argument will get the actual item
    var tr_str = "<tr>"
    + "<td>" + item.n_title + "</td>"
    + "<td>" + item.n_dateTime + "</td>"
    + "<td><button class='btn btn-danger delete-btn' data-id='" + item.id + "'>Delete</button></td>";
     $( "#output" ).append(tr_str);
}); 

Adding the event on the class .delete-btn inside the callback will add multiple events on buttons that already exists on the page.