简体   繁体   English

使用ajax提交表单后如何重新加载数据表?

[英]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.这是我用于添加 json 对象的 ajax 代码。 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.我没有成功使用 DataTable 的内置 API。 I kept receiving "invalid JSON" error and it wouldn't load the table.我一直收到“无效的 JSON”错误,它不会加载表。 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({ ..}); 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.保持上面两步的功能,从你的数据接收的ajax成功函数中调用。

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()有关更多信息,请查看此链接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.我假设这个https://datatables.net就是你的意思。 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.实际上,Datatables 有一个 API,无需重新加载整个表。 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参考: https : //datatables.net/examples/api/add_row.html

You can append the data to the DOM with your success param.您可以使用success参数将数据附加到 DOM。

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).确保process.php返回一些东西(在你的例子中是一个表)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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