I'm writing a little wordpress plugin. The plugin has a simple script that interacts with a datatable in the backend.
It is used to duplicate a row in the table by clicking a button, and then insert the data in the database.
I'm using a setTimeout(function () {}
because the table loads through ajax, and i need to wait that the button is in the DOM.
It works, but only on the first click, nothing happens if i click the button a secon time, i have to referesh the page to make it working again.
here is my code:
setTimeout(function () {
var duplicate = $('#wpbody-content').find("[data-action=duplicate]");
duplicate.each(function() {
$(this).on('click', function() {
//console.log('click');
var rate = $(this).parent().parent().next().find('.custom-control-input').val();
//console.log(value);
$.ajax({
url: '/wp-admin/admin-ajax.php',
data: {
action: 'duplicate_row',
'duplicate_ajax': rate
}, success: function(data){
//console.log('SUCCESS');
$('#my-table').DataTable().ajax.reload(null, false);
}
});
});
});
}, 3000);
I would wrap it in a function so like this it can be called on demand.
it would be better to add a class to each element
duplicate
and then call it like that.Also to not it is better to define you ajax url on the page via PHP so there is a consistency when you call wordpress ajax.
Then in your js: