简体   繁体   中英

How to reload data table after submitting a form using ajax?

The table is already displayed and an "add" button is on top of that table. What I wanted to do is to reload the table after submitting the modal form that I have.

Here's my ajax code for adding a json object. I'm pretty sure that the solution will also be inside this.

$('#btnSubmit').click(function(event) {
        var formData = {
            'name'         : $('[name=name1]').val(),
            'address'      : $('[name=bAddress1]').val(),
            'officer'      : $('[name=officer1]').val(),
            'contactnumber': $('[name=contactN1]').val()
        };

        $.ajax({
            type        : 'POST',
            url         : "process.php",
            data        : formData,
            dataType    : 'json',
            encode      : true,
            success     : function(r){
                             var status = "1";
                             alert (status);          
                             },
            dataType: "html"
        });        
});

And here is where I load the table

<div class="container">
....
</div>

The question is: How can I reload the table after submitting a form?

I was trying this myself tonight. I did not succeed using DataTable's built in API for it. I kept receiving "invalid JSON" error and it wouldn't load the table. See below for my sample code that I got to work.

$(document).ready(()=> {
    // wait for page to load
    let userid = 12345;
    function loadtbl() {
      $.get("data.php?userid=" + encodeURIComponent(userid), (data)=> {
        // initialize datatable with your specified parameters
        $("#exampletbl").DataTable({});
      }):
    }
    // The table will not load unless if you call on the function which is done below
    loadtbl();
    // Submit new data to back end and then reload table
    $("#form").submit((event)=> {
      $.post("data.php", {username: $("#username").val()}, (data)=> {
        // Destroy the table the reload it
        $("#contactstbl").DataTable().destroy();
        loadtbl();
      });
      event.preventDefault();
    });
  });

I hope this helps!!

If you want to reload data table steps to follow

Assuming your initial table initiation is like below

var myTable = $("#tableId").DataTable({ ..});

  1. Destroy the previous instance of table.

     myTable = $("#tableId").DataTable(); myTable.destroy();
  2. Initialize table again with newly received data.

     myTable = $("#tableId").DataTable({ ......... //Your table parameters });

Keep the above two steps in function and call it from your ajax success function of data receiving.

This is not the only way to load data but its simple to follow. :)

Try This

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

For Further Information check this link https://datatables.net/reference/api/ajax.reload()

Base on your title, you said "data tables". I assume this https://datatables.net is what you mean. If I'm right.

The table is already displayed and an "add" button is on top of that table

I think what you are trying to achieve in reloading your table is to add the new row in your table. Actually, Datatables have an API for that without reloading your whole table. More efficient.

$('#btnSubmit').click(function(event) {
    var n = $('[name=name1]').val();
    var a = $('[name=bAddress1]').val();
    var o = $('[name=officer1]').val();
    var c = $('[name=contactN1]').val()
    var formData = {
        'name'         : n,
        'address'      : a,
        'officer'      : o,
        'contactnumber': c
    };

    $.ajax({
        type        : 'POST',
        url         : "process.php",
        data        : formData,
        dataType    : 'json',
        encode      : true,
        success     : function(){
                            $('#yourTable').DataTable().row.add([
                               n,
                               a,
                               o,
                               c
                            ]).draw( false );
                         },
        dataType: "html"
    });        
});

Reference: https://datatables.net/examples/api/add_row.html

You can append the data to the DOM with your success param.

This is how your code would look like:

$.ajax({
    type        : 'POST',
    url         : "process.php",
    data        : formData,
    dataType    : 'json',
    encode      : true,
    success     : function(data){
                     $('.container').html(data); // <--- append data to div  
                     },
    dataType: "html"
}); 

Be sure that process.php returns something(in your case a table).

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