datatable jquery edit button code example
Example: add edit button to datatable
$(document).ready(function(){
var userDataTable = $('#userTable').DataTable({
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'ajax': {
'url':'ajaxfile.php'
},
'columns': [
{ data: 'name' },
{ data: 'email' },
{ data: 'gender' },
{ data: 'city' },
{ data: 'action' },
]
});
$('#userTable').on('click','.updateUser',function(){
var id = $(this).data('id');
$('#txt_userid').val(id);
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 2, id: id},
dataType: 'json',
success: function(response){
if(response.status == 1){
$('#name').val(response.data.name);
$('#email').val(response.data.email);
$('#gender').val(response.data.gender);
$('#city').val(response.data.city);
userDataTable.ajax.reload();
}else{
alert("Invalid ID.");
}
}
});
});
$('#btn_save').click(function(){
var id = $('#txt_userid').val();
var name = $('#name').val().trim();
var email = $('#email').val().trim();
var gender = $('#gender').val().trim();
var city = $('#city').val().trim();
if(name !='' && email != '' && city != ''){
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 3, id: id,name: name, email: email, gender: gender, city: city},
dataType: 'json',
success: function(response){
if(response.status == 1){
alert(response.message);
$('#name','#email','#city').val('');
$('#gender').val('male');
$('#txt_userid').val(0);
userDataTable.ajax.reload();
$('#updateModal').modal('toggle');
}else{
alert(response.message);
}
}
});
}else{
alert('Please fill all fields.');
}
});
$('#userTable').on('click','.deleteUser',function(){
var id = $(this).data('id');
var deleteConfirm = confirm("Are you sure?");
if (deleteConfirm == true) {
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 4, id: id},
success: function(response){
if(response == 1){
alert("Record deleted.");
userDataTable.ajax.reload();
}else{
alert("Invalid ID.");
}
}
});
}
});
});