0
votes

I want to reload the datatable after I insert the new data in the database. I have written this code of HTML.

<table class="table table-striped table-bordered bootstrap-datatable datatable" id="Slider_table">
<thead>
    <tr>
        <th>Title</th>
        <th>Price</th>
    </tr>
</thead>
<tbody>
    <?php foreach($items as $row){?>
    <tr>
        <td><?=$row->item_title;?></td>
        <td class="center"><?=$row->item_price;?></td>
   </tr>
</tbody>

But it gives me that error in the console.log.

Uncaught TypeError: Cannot read property 'reload' of undefined on that line $("#Slider_table").DataTable().ajax.reload();

$('#add_items').on('click', function(e){
    e.preventDefault();
    var formData = new FormData($("#form1")[0]); //It automatically collects all fields from form

    $.ajax({
        url: "<?= base_url(); ?>Items/add_items",
        type: "post",
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function(output) {
            $("#Slider_table").DataTable().ajax.reload();
        }
    });
});
2
reload is available in version 1.10.0,what version you are using?Deepak A
'reload' of undefined means that it's not availability of reload. there's something wrong with .ajax at least.Chase Choi
@Deepak i am using latest versionWaqas Ahmad

2 Answers

1
votes

You have to store the datatable reference in one variable. And as per the code you have used you can't use datatable ajax reload method.

So you have to apply below solution:

Define table variable: var table;

and load the datatable like this on document ready function.

table = $("#Slider_table").DataTable();

$('#add_items').on('click', function(e){
    e.preventDefault();
    var formData = new FormData($("#form1")[0]); //It automatically collects all fields from form

    $.ajax({
        url: "<?= base_url(); ?>Items/add_items",
        type: "post",
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function(output) {
            table.row.add($(output)).draw();
            // Here in output you have to return table rows html from php

        }
    });
});
0
votes

you can use

  dtable.draw();

after success. it will refresh your datatable