简体   繁体   中英

How to update/refresh datatable after an ajax update or insert call?

I have this table right here that is populated by query results from my database:

<div class="card-block">
    <table id="catTbl" class="display" width="100%" cellspacing="0"  data-toggle="modal" data-target="#cat-update">
         <thead>
             <tr>
                 <th>ID</th>
                 <th>Title</th>
             </tr>
         </thead>
         <tbody>
             <?php
                 include "../processes/getLists.php";
                 $process = new getLists();
                 $process->getCatForTbl();
                 //used PHP PDO for that
             ?>
         </tbody>
      </table>
      <p id="message" style="margin-top: 15px"></p>
</div>

I can properly update and insert rows in the database using ajax so the page won't load every after process but the problem is if I don't reload my page after every insert/update the datatable won't update with the newly updated/inserted rows.

I tried $("#catTbl").ajax.reload() , $("#catTbl").clear().draw() but they won't work unless my table is somehow made up of json . Is there anything I can do for my table to reload every after ajax call? Add: I don't want the whole page to reload, just the datatable on submit event.

$('#updateCatForm').on("submit", function(event){
    event.preventDefault();
    $.ajax({
        url:"../ajax/updateCat.php",
        method:"POST",
        data:$('#updateCatForm').serialize(),
        success:function(data){
            $('#updateCatForm')[0].reset();
            $('#cat-update').modal('hide');
            $('#message').html(data);
            //I put the table reload solutions here and nothing seemed to work :<
        }
    })
});

Use this

$('#example').DataTable().ajax.reload();

Make sure the selector is same. Or you can simply store in a variable and use it like this

var table = $('#example').DataTable();

Then after ajax

table.ajax.reload();

---Edit----

table.ajax.reload({
    "ajax": {
           "url": '${ctx}/work/list_ajax.json',
           "type": 'POST',
           "data":{ 
              data:$('form').serialize()
           }
    } 
});

I'm not entirely sure about this, I didn't give it a try but it's something along this line to get the data and display on the table. I'm sorry I couldn't provide you with a working snippet. Remeber the returned data should be in a proper format or it won't work.

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