Table doesn't refresh with table.ajax.reload(), when used after a delete operation is performed on a row

Viewed 1205

I have a table which is printing data in this form,

var table; 
  // DATA TABLE!!!
function show_assigned_table()
{
  $.ajax({
      url: "action.php", 
      type: "POST", 
      data: {action:"view_assigned_course_table"}, 
      dataType: 'json', 
    success: function(data)
    {
      console.log(data);
      table = $('#assign_table').DataTable({
        "bDestroy": true,
        data: data, 
        columns: [
        {'data': 'course_name'},
        {'data': 'teacher_name'},
        {'data': 'grade_name'},
        {'render': function(data, type, row, meta){
                    return '<a id="replace_teacher' + meta.row + '" data-value = ' + row.taught_id +
                            ' class="btn btn-outline-warning btn-sm" href="">Replace</a>&nbsp;&nbsp;<a id="remove_teacher' +
                            meta.row + '" data-value = ' +
                            row.taught_id + ' class="btn btn-outline-danger btn-sm" href="">Delete</a>';
        }},
        
        ]
      });

    },
    error: function(e)
    {
      alert("no");
    }
  });
}

Now, I have another function for the "Replace" and "Delete" buttons. A function for delete button is as follows,

 $(document).on("click", "[id^=remove_teacher]", function(e){
    var id = $(this).data('value');
    e.preventDefault(); 
    $.ajax({
      url: "action.php", 
      type: "POST", 
      data:{action: "Remove_Assigned_Teacher", id: id}, 
      success:function(response)
      {
        response = response.trim(); 
        console.log(response);
        if (response == 'ok')
        {  
          alert("Teacher has been removed from the course successfully!"); 
          $("#assign_table").DataTable().ajax.reload(); 
        }
          
        else 
          alert("Error occured"); 
      }
        
      });
    });

This function works well, except one thing, it doesn't Refresh the table whenever a row is deleted... To refresh the table, I have to refresh the whole page. What I want is only this table to be refreshed whenever the delete event occurs.

I used ajax.reload() function for this but it didn't work, as it apparently didn't receive JSON data on refresh (now I tried to search it but I couldn't find any thing which I could properly understand. I did find a code to convert array to JSON but didn't get how to implement it in my code. I am still very new in this).

I also tried using destroy function and then created the table again, that worked but it destroyed all the properties of my table (like the border of table, search bar and etc. The look of the table changed)

1 Answers

Your issue is in this line:

$("#assign_table").DataTable().ajax.reload()

Your datatable has no ajax option, hence you get an error in the console:

jquery.dataTables.min.js:50 Uncaught TypeError: Cannot set property 'data' of null

Because you control the datatable client side, using jquery ajax, you need to use datatable row remove() in order to delete a row, i.e.:

$('#assign_table').DataTable().row( $(this).closest('tr')).node().remove()

If instead you wish to control everything server side you need to use the datatable ajax option and change a bit the logic of your sw. In this case I would suggest you to take a look to Removing rows with ajax Data

var data = [
    {
        "taught_id": "11",
        "course_name": "English",
        "grade_name": "2",
        "section_name": "A",
        "teacher_name": "Ali Khalil"
    },
    {
        "taught_id": "6",
        "course_name": "Science",
        "grade_name": "2",
        "section_name": "A",
        "teacher_name": "Talha Ayub"
    },
    {
        "taught_id": "8",
        "course_name": "Science",
        "grade_name": "7",
        "section_name": "A",
        "teacher_name": "Talha Ayub"
    }
];
function show_assigned_table() {
    /*
     $.ajax({
     url: "http://localhost:63342/StackOverflow/1.json",
     type: "POST",
     data: {action:"view_assigned_course_table"},
     dataType: 'json',
     success: function(data) {
     */
    $('#assign_table').dataTable({
        data: data,
        columns: [
            {'data': 'course_name'},
            {'data': 'teacher_name'},
            {'data': 'grade_name'},
            {
                'render': function (data, type, row, meta) {
                    return '<a id="replace_teacher' + meta.row + '" data-value = ' + row.taught_id +
                            ' class="btn btn-outline-warning btn-sm" href="">Replace</a>&nbsp;&nbsp;<a id="remove_teacher' +
                            meta.row + '" data-value = ' +
                            row.taught_id + ' class="btn btn-outline-danger btn-sm" href="">Delete</a>';
                }
            }
        ]
    });
    /*
     },
     error: function(e) {
     alert("no");
     }
     })
     */
}
$(document).on("click", "[id^=remove_teacher]", function (e) {
    var response = {
        "data": "ok"
    };
    e.preventDefault();
    var crow = $('#assign_table').DataTable().row( $(this).closest('tr')).node();
    var id = $(this).data('value');
    console.log('taught_id --> ' + id);
    //$.ajax({
        //url: "http://localhost:63342/StackOverflow/2.json",
        //type: "POST",
        //data: {action: "Remove_Assigned_Teacher", id: id},
        //success: function (response) {
            response = response.data.trim();
            console.log(response);
            if (response == 'ok') {
                //alert("Teacher has been removed from the course successfully!");
                crow.remove();
            }
            else
                alert("Error occured");
        //}
    //});

});
show_assigned_table();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>

<table id="assign_table" class="display" style="width:100%">
    <tbody>
    </tbody>
</table>

Related