如何通过ajax添加数据后重新加载数据?

时间:2016-10-12 10:20:56

标签: javascript jquery ajax datatable

我有一个通过ajax将数据添加到数据库的UI。该数据应反映在我的数据表中,而无需重新加载整个页面或仅重新加载数据表。我尝试过使用t.api().ajax.reload()& t.ajax.reload()但它会在控制台中抛出错误,例如“无法读取属性'重新加载'未定义”或“ t.api不是函数”我不知道这里做错了什么。以下是一些参考

用户界面 - 通过添加角色btn添加数据,这会带来弹出

enter image description here

添加角色弹出

enter image description here

HTML

    <div id="roles" style="display: block" >   
                <ul class="tab-onebtn">
                    <li class="logouttab"> <a  style="float: left;" id="myBtn"> Add Role </a> </li>
                </ul>  

                <div class="table roles_table" >
                    <table class="example display" id="mytable" cellspacing="0" width="100%">
                       <thead>
                        <tr>
                            <th>Roles</th>
                            <th>Action</th>
                        </tr>
                       </thead> 
                       <tbody>
                  <?php foreach($resultRoles as $r) { ?>
                        <tr>
                            <td><?php echo $r->cptv_role; ?></td>
                            <td></td>  
                        </tr>
                  <?php } ?>     
                       </tbody>
                    </table>  
                </div>



              <h1> Roles coming soon</h1>

              </div>

<div id="myModal" class="modal" >

  <!-- Modal content -->
  <div class="modal-content">
      <span class="close">×</span>

<!--  <div class="modal-header">
    <h2 style="text-align:center";>Add Role</h2>
  </div>-->
  <div class="modal-body">

    <form action="" method="post" class="addRoleForm">
           <?php if(!empty($this->session->flashdata('error')) ) {  ?><div class='error' style="margin-top: -20px;"><h2><?php echo $this->session->flashdata('error');  ?> </h2></div><?php } ?>
           <?php if(validation_errors() != false) {  ?><div class='error'><?php echo validation_errors(); ?></div><?php } ?>
            <div class="field-wrap">

            <label>
              Role <span class="req">*</span>
            </label>
            <input name="role" class="roleInput" type="text"required autocomplete="off"/>

          </div>

           <div id="result" class="msg" style="display:none;"></div>

          <button class="button button-block submitbtn"/><span class="addRole" >Add Role </span> <span class="Added" style="display:none;"><b>Successfully Added </b></span></button>

    </form>


  </div>
<!--  <div class="modal-footer">
    <h3>Modal Footer</h3>
  </div>-->
</div>

</div>

的Javascript

// Ajax post
$(document).ready(function() {
  var  t = $('#mytable').DataTable();
$(".addRoleForm").submit(function(){  
event.preventDefault();
var str = $(this).serialize(); 
console.log();
jQuery.ajax({
type: "POST",
url: base_url+ "admin/roles/addRole",
dataType: 'json',
data: str,
success: function(result) {
if (result)
{
   console.log(result);
// Show Entered Value
jQuery("div#result").show();
if(result.success){
//    $('#mytable tbody').append('<tr><td>'+$('input[name="role"]').val().trim()+'</td><td></td></tr>');
//    $('#mytable').DataTable();
t.api().ajax.reload();
jQuery("div.msg").html("<div class='success'><h2>"+result.success+"</div>");
setTimeout(function(){
    span.click();
    }, 2000);

}else{
   jQuery("div.msg").html("<div class='error'><h2>"+result.error+"</h2></div>"); 
}
//var ref = $('#mytable').DataTable(); 
//setInterval( function () {
//    ref.ajax.reload(); // user paging is not reset on reload
//}, 1000 );

 setTimeout(function(){
  jQuery("div#result").hide();
  $(".roleInput").val('');

 }, 2000);

}
}
});
});
});

控制器

public function addRole() {

         if (empty($this->sessionData)){
//            print_r($this->sessionData['id']); exit;
            $this->index();
        }


        $post = $this->input->post();
        $this->form_validation->set_rules('role', 'Role', 'trim|required|xss_clean');
        if ($this->form_validation->run()) {
            $roleDet = $this->roles_model->checkCpRoles(array('cptv_role' => $post['role']));
            if ($roleDet->num_rows()) {
                $data['error'] = " Role already Exist.";
                echo json_encode($data);
            } else {
                $result = $this->roles_model->addCpRoles(array('cptv_role' => $post['role']));
                if ($result){
                $data['success'] = " Successfully added the Role ";
                echo json_encode($data);
                } else {
                    $data['error'] = " Something went wrong ";
                echo json_encode($data);
                }

            }

        }



    }

有人可以帮帮我吗?

3 个答案:

答案 0 :(得分:0)

在ajax成功之后重新加载数据表,如:

您正在使用旧的API:$()。dataTable()(v1.9及更早版本),它仍可在DataTables v1.10中使用。旧的API返回jQuery对象,因此您应该使用.api()来使用DataTable API方法:

oTable.api().ajax.reload();
// where oTable is the reference to datatable.

答案 1 :(得分:0)

因为你已经在php中编写了一些代码,所以我不太了解它,但我可以在你的代码中指出这个问题。你有一个t.api().ajax.reload();

您的代码make sure all the columns are returned, right now you have only 2 columns in your table因为DataTable没有通过ajax获取数据而中断,这意味着您的DataTable没有针对基于ajax的数据设置,它是一个普通的HTML表格

我建议您在ajax成功方法中返回需要附加到表(t.row.add(yourArrayGoesHere).draw( false ); )中的整行。现在,您只需将此新列添加到dataTable并重绘表

将新行添加到dataTable并重绘它的语法如下所示。

["Admin",""]

这意味着来自服务器的响应必须是数组。示例: t.row.add(["Admin",""]).draw( false );

测试:在浏览器中打开控制台窗口(按F12打开) 并粘贴此代码并按Enter键。您必须能够看到第一个单元格具有值Admin的新行。

{{1}}

如果有帮助,请告诉我。

答案 2 :(得分:0)

这是我见过的最好的例子,其中数据表是用Codeigniter framweork实现的。

http://mbahcoding.com/tutorial/php/codeigniter/codeigniter-ajax-crud-using-bootstrap-modals-and-datatable.html