简体   繁体   English

如何使用表单提交将数据提取到jquery dataTable

[英]How to fetch data to jquery dataTable with form submit

I am inserting data with jquery Ajax using form submit, And fetching data to dataTable after form submit, following code giving DataTables warning: table id=mainTable - Requested unknown parameter '1' for row 0, column 1. . 我使用表单提交在jquery Ajax中插入数据,并在表单提交后将数据提取到dataTable,后面的代码给出DataTables警告:table id = mainTable - 第0行,第1列请求的未知参数'1'。 . . .

var mainTable = $('.mainTable').DataTable();
$('#Form').submit(function(e) {
  e.preventDefault();
  var form = $(this).serialize();
    $.ajax({
        url: "result.php",
        type: "post",
        data: form 
  }).done(function (data) {
        mainTable .clear().draw();
        mainTable .rows.add(data).draw();
        }).fail(function (jqXHR, textStatus, errorThrown) { 
        });
});

HTML HTML

<div class="content">
    <!-- form start -->
    <form method="post" id="Form">     

            <input type="text" name="id">
            <input type="text" name="name">
            <input type="text" name="class">

        <button type="submit">submit</button>
    </form> 


<table id="mainTable" class="mainTable table table-striped">
  <thead>
    <tr>
      <th>Roll No</th>
      <th>Name</th>
      <th>class</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
</div>

PHP PHP

$id = $_POST['group_id'];
$rollno = $_POST['roll_no'];
$name = $_POST['name'];
$class = $_POST['class'];

$insert = "insert into students (roll_no,group_id,name,class) values(:roll_no,:id,:name,:class)";
$insert = $db->prepare($insert );
$insert ->bindParam(':roll_no',$rollno);
$insert ->bindParam(':id',$id );
$insert ->bindParam(':name',$name);
$insert ->bindParam(':class',$class);
$insert ->execute();

$fetch = "SELECT roll_no,name,class FROM students where group-id=:id";
$fetch = $db->prepare($fetch );
$fetch ->bindParam(':id',$id);
$fetch ->execute();

$output = array('data' => array());
while($row = $fetch ->fetch(PDO:: FETCH_OBJ)) {

    $id = $row->roll_no;
    $name = $row->name;
    $class = $row->class;
$output['data'][] = array( $id,$name,class);    
} // /while 

echo json_encode($output);

Moved from comment 从评论中移出

The root cause is simply because jQuery ajax() doesn't parse the JSON response from result.php . 根本原因仅仅是因为jQuery ajax()不解析result.php的JSON响应。 The easiest solution is to parse it inside done() : 最简单的解决方案是在done()解析它:

data = JSON.parse(data);
mainTable.rows.add(data.data).draw();

Another solution is to properly return JSON header in result.php . 另一种解决方案是在result.php正确返回JSON头 Line data = JSON.parse(data) in done() should also be omitted: 还应省略在done()data = JSON.parse(data)

header('Content-Type: application/json');
echo json_encode($output);

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

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