简体   繁体   中英

how to refresh jquery datatable after ajax call

Using jquery data table i am loading the data but once a row i am deleting using ajax call if the call is successful then it has to reload the data. Below is the attached code where in the ajax call section I have to insert the refresh table logic once call is success.

<html>
<head>
<script src="http://localhost:1880/images/jqueryjs.js"></script>
<link rel="stylesheet" type="text/css" href="http://localhost:1880/images/jquerycss.css">
<script type="text/javascript" charset="utf8" src="http://localhost:1880/images/datatable.js"></script>
<script>

/* Formatting function for row details - modify as you need */
function format ( d ) {
    // `d` is the original data object for the row
    return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
       '<tr>'+
            '<td>Full name:</td>'+
            '<td>'+d.lat+'</td>'+
        '</tr>'+
        '<tr>'+
            '<td>Extension number:</td>'+
            '<td>'+d.lon+'</td>'+
        '</tr>'+
        '<tr>'+
            '<td>Alert Type</td>'+
            '<td>'+d.alertExtraInformation1+'</td>'+
        '</tr>'+
    '</table>';
}

$(document).ready(function() {
    var table = $('#example').DataTable( {
        ajax:{ url:'http://localhost:9003/BPMNProcessInfo/1.0.0/getAlerts',dataSrc:""},
        scrollY:        250,
        deferRender:    true,
        scroller:       true,
         "columns": [
            {
                "class":          'details-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": ''
            },
            { "data": "id" },
            { "data": "alertname" },
            { "data": "devicename" },
            { "data": "time" },
            {
                "class":          'details',
                "orderable":      false,
                "data":           null,
                "defaultContent": ''
            },
            {
                "class":          'send',
                "orderable":      false,
                "data":           null,
                "defaultContent": ''
            }

        ],
        "order": [[1, 'asc']]
    } );

    $('#example tbody').on('click', 'td.details', function(){

        var tr = $(this).closest('tr');
        var row = table.row( tr ).data();
        console.log(row);
        $.ajax({
  type: "DELETE",
  contentType: "application/json; charset=utf-8",
  url: "http://localhost:9003/BPMNProcessInfo/1.0.0/delteAlert/"+row.id,

});

    //code to refresh the page
    //
    //

    });

    // Add event listener for opening and closing details
    $('#example tbody').on('click', 'td.details-control', function(){
        var tr = $(this).closest('tr');
        var row = table.row( tr );

        if(row.child.isShown()){
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
        } else {
            // Open this row
            row.child(format(row.data())).show();
            tr.addClass('shown');
        }
    });

    $('#example tbody').on('click', 'td.details', function(){

        var tr = $(this).closest('tr');
        var row = table.row( tr ).data();
        console.log(row);

    });

    // Handle click on "Expand All" button
    $('#btn-show-all-children').on('click', function(){
        // Enumerate all rows
        table.rows().every(function(){
            // If row has details collapsed
            if(!this.child.isShown()){
                // Open this row
                this.child(format(this.data())).show();
                $(this.node()).addClass('shown');
            }
        });
    });

    // Handle click on "Collapse All" button
    $('#btn-hide-all-children').on('click', function(){
        // Enumerate all rows
        table.rows().every(function(){
            // If row has details expanded
            if(this.child.isShown()){
                // Collapse row details
                this.child.hide();
                $(this.node()).removeClass('shown');
            }
        });
    });
});

</script>
<style>
td.details-control {
    background: url('https://cdn.rawgit.com/DataTables/DataTables/6c7ada53ebc228ea9bc28b1b216e793b1825d188/examples/resources/details_open.png') no-repeat center center;
    cursor: pointer;
}
tr.shown td.details-control {
    background: url('https://cdn.rawgit.com/DataTables/DataTables/6c7ada53ebc228ea9bc28b1b216e793b1825d188/examples/resources/details_close.png') no-repeat center center;
}
#btn-show-all-children{
color: black;
width: 49.5%;
border-radius: 2px;
background-color: #AD1625;
}
#btn-hide-all-children{
color: black;
width: 49.5%;
border-radius: 2px;
background-color: Green;
}
table, th , td  {
  border: 2px solid black;
  border-collapse: collapse;
  padding: 5px;
}
th{
background-color:#6b6767;
color:white;
}
td{
background-color: #FFF;
}
td {
    background-color: #FFF;
    color: white;
}
table.dataTable.display tbody tr.odd>.sorting_1, table.dataTable.order-column.stripe tbody tr.odd>.sorting_1 {
    background-color: #FFF;
    color: white;
}

table.dataTable.display tbody tr.even>.sorting_1, table.dataTable.order-column.stripe tbody tr.even>.sorting_1 {
    background-color: #FFF;
    color: white;
}
div.dataTables_scrollBody>table>tbody>tr>td {
    vertical-align: middle;
    background-color: #5a5757;
    color: white;
}
td {
    background-color: #3e3b3b;
    color: white;
}
table.dataTable.display tbody tr.odd>.sorting_1, table.dataTable.order-column.stripe tbody tr.odd>.sorting_1 {
    background-color: #5a5757;
    color: white;
}

table.dataTable.display tbody tr.even>.sorting_1, table.dataTable.order-column.stripe tbody tr.even>.sorting_1 {
    background-color: #5a5757;
    color: white;
}
div.dataTables_scrollBody>table>tbody>tr>td {
    vertical-align: middle;
    background-color: #5a5757;
    color: white;
}
.nr-dashboard-theme .nr-dashboard-template ::-webkit-scrollbar {
    height: 12px;
    width: 12px;
    background: #820f0f;
}
.nr-dashboard-theme .nr-dashboard-template ::-webkit-scrollbar-thumb {
    background: #eadede;
    -webkit-border-radius: 1ex;
    -webkit-box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.75);
}
#btn-show-all-children,#btn-hide-all-children {
  background-color: #4CAF50; /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  float: left;
}

#btn-show-all-children,#btn-hide-all-children {
  background-color: #3e8e41;
}

.dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_processing, .dataTables_wrapper .dataTables_paginate {
    color: #e4d8d8;
}

.dataTables_wrapper .dataTables_paginate .paginate_button.disabled, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:hover, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:active {
    cursor: default;
    color: #f1ebeb !important;
    border: 1px solid transparent;
    background: transparent;
    box-shadow: none;
}
.dataTables_wrapper .dataTables_paginate .paginate_button {
    box-sizing: border-box;
    display: inline-block;
    min-width: 1.5em;
    margin-left: 2px;
    text-align: center;
    cursor: pointer;
    color: rgb(255, 255, 255) !important;
    padding: 0.5em 1em;
    border-width: 1px;
    border-style: solid;
    border-color: transparent;
    border-image: initial;
    border-radius: 2px;
    text-decoration: none !important;
}

td {
    background-color: #130101;
    color: #ffffff;
}
td.details {
    background: url('http://localhost:1880/images/delete.PNG') no-repeat center center;
    cursor: pointer;
}
td.send {
    background: url('http://localhost:1880/images/send-button.PNG') no-repeat center center;
    cursor: pointer;
}
</style>
</head>
<body>

<hr>
<table id="example" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th></th>
            <th>Id</th>
            <th>Alert Name</th>
            <th>Device Name</th>
            <th>Time</th>
            <th>Delete</th>
            <th>Send To Workforce</th>
        </tr>
    </thead>

</table>
</body>
</html>

For refreshing the table I have used table.ajax.reload(); and also table.fnDraw(false); but it is not working. How to refresh the datatable.

Chain the .then() call onto your $.ajax() call. It's preferrable over .done() or .fail() because it catches both. You can test the response by logging it to the console or use it by rendering it to the DOM or by using some sort of application-wide state (like Vue, React/Redux, or Angular). It's a Promise, so it takes two functions as arguments.

ie.

$.get( "test.php" ).then(
  function() {
    alert( "$.get succeeded" );
  }, function() {
    alert( "$.get failed!" );
  }
);

or, in your case

$.ajax({
  type: "DELETE",
  contentType: "application/json; charset=utf-8",
  url: "http://localhost:9003/BPMNProcessInfo/1.0.0/delteAlert/"+row.id,
}).then(function() {
  alert( 'Success!' );
}, function() {
  alert( 'fail' );
})

.ajax() DOCS: http://api.jquery.com/jquery.ajax/

.then() DOCS: http://api.jquery.com/deferred.then/

$.ajax have done option that calls a function. In that function you can call whatever you want to call:

$.ajax({
  type: "DELETE",
  contentType: "application/json; charset=utf-8",
  url: "http://localhost:9003/BPMNProcessInfo/1.0.0/delteAlert/"+row.id
 }).done(function() {
    table.ajax.reload();
 });

The general essence is such that after executing the request to the specified address, the success callback will work if the request is successful:

     $.ajax({
        type: "DELETE",
        contentType: "application/json; charset=utf-8",
        url: "http://localhost:9003/BPMNProcessInfo/1.0.0/delteAlert/"+row.id,
        success: function(data_response){
            if(data_response.error <= 0 || data_response.error !== null){ //if you send data after query result
                //update all you need
            }
        },
        error: function(){
            //if error ajax
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM