在文件上传ajax之后向dataTable添加新行

时间:2015-09-12 21:24:02

标签: php jquery datatables

我修好了,请参阅下面的答案

我有一个数据表,我通过php填写,显示所有上传的文件和一些打开模式查看/编辑/删除的按钮。文件上传在同一页面上完成,如果再次加载页面,则当前显示新上载的文件。我希望通过在上传完成后(在Ajax调用成功时)向表中添加一行来显示上传的文件。

我怎样才能做到这一点?

以下是我目前的代码:

<!--    How I fill the table first       -->
<?php

$search = 'SELECT Id, Document, title, event_access, position_access, position_categories, status FROM $briefing WHERE Event_ID = ? ORDER BY Id DESC';
if($Result = $conn->prepare($search)) {
    if ( false === $Result ) {
        die('prepare() failed: ' . htmlspecialchars($conn->error));
    }
    $Result->bind_param('i', $cceveid_request);
    $Result->execute();
    $Result->store_result();
    $Result->bind_result($Id, $Document, $title, $event_access, $position_access, $position_categories, $status);

    $num_rows = $Result->num_rows;
?>

<table id="datatable_brief" data-ride="datatables">
<thead class="border-bottom-grey border-top-grey">
  <tr>
    <th width="20%" class="line-right table-sv_coordinator">Item</th>
    <th width="20%" class="line-right table-sv_coordinator">Permissions</th>
    <th width="20%" class="line-right table-sv_coordinator">Status</th>
    <th width="20%" class="line-right table-sv_coordinator" style="border-right: none">Action</th>
  </tr>
</thead>
<tbody>
<div id="erroreditstat"></div>

<?php  if($num_rows > 0 ){
    while ($Result->fetch()) {
      if ($event_access !== "Available for all") {
        $event_access = json_decode($event_access);
      }

      if ($position_access !== "Available for all") {
        $position_access = json_decode($position_access);
      }

      if ($position_categories !== "Available for all") {
        $position_categories = json_decode($position_categories);
      }

     $DocumentName = "";
     $original_filename = $Document;
     $DocumentName =  substr( $original_filename, strpos( $original_filename, '-') + 1);
?>
<tr class="<?php echo $Id; ?>">
    <td width="20%" class="padding5p">
        <?php echo $title; ?>
    </td>
    <td width="20%" class="padding5p">
        <a class="btnView" 
        data-id="<?php echo $Id; ?>"
        data-docname="<?php echo $DocumentName; ?>"
        data-title="<?php echo $title; ?>"
        data-eventaccess="<?php echo $event_access; ?>"
        data-posaccess="<?php echo $position_access; ?>"
        data-poscataccess="<?php echo $position_categories; ?>"
        data-status="<?php echo $status; ?>">View</a>

        <a class="btnEdit" 
        data-id="<?php echo $Id; ?>"
        data-eventaccess="<?php echo $event_access; ?>"
        data-posaccess="<?php echo $position_access; ?>"
        data-poscataccess="<?php echo $position_categories; ?>"><i class="fa fa-pencil"></i> Edit</a>
    </td>
    <td width="20%" class="padding5p">

        <span class="personal_detail_holder" data-hold="<?php echo $Id; ?>" id="personal_briefStatus_holder">
            <?php if($status=='Active')echo 'Active';else echo 'Inactive';?>
        </span>

        <a class="btn_personal_edit" editfor="personal_briefStatus" id="personal_briefStatus_btn_edit" data-id="<?php echo $Id; ?>" href="javascript:void(0)" onclick="showField(this.id,$(this).attr('data-id'))">
            <i class="fa fa-pencil"></i> Edit
        </a>

        <div class="personal_detail_edit_box" data-holder="<?php echo $Id; ?>" id="personal_briefStatus_btn_edit_box" style="display:none;">
            <select class="form-control m-b" name="briefStatus" data-save="<?php echo $Id; ?>" id="briefStatus">
                <option value="Active" <?php if($status=='Active') echo 'selected="selected"';?>>Active</option>
                <option value="Inactive" <?php if($status=='Inactive') echo 'selected="selected"';?>>Inactive</option>
            </select>
            <div style="clear:both"></div>
            <div class="align-center">
                <a class="btn_personal_save" editfor="personal_briefStatus" href="Javascript:void(0)" onclick="editData('briefStatus','personal_briefStatus','<?php echo $Id; ?>');">Save</a> - 
                <a class="btn_personal_cancel" data-cancel="<?php echo $Id; ?>" editfor="personal_briefStatus" href="javascript:void(0)"  onclick="cancelField('personal_briefStatus', '<?php echo $Id; ?>');">Cancel</a>
            </div>
        </div>

    </td>
    <td width="20%" class="padding5p">
        <a class="btnDelete" data-id="<?php echo $Id; ?>" style="float:left;"><i class="fa fa-remove text-danger text"></i> Delete</a>
    </td>
    </tr>
<?php
        }
    }
}
?>
</tbody>
</table>
<!-- Initial datatable js  & file upload function -->


<script type="text/javascript">
$( document ).ready(function() {
    $('#datatable_brief').dataTable({"sPaginationType": "full_numbers","aaSorting": [[0,'desc']],"dom":' <"search"f><"top"l>rt<"bottom"ip><"clear">'});
});

function submitNew(e){
    e.preventDefault;
    var value = $("#Document").val();
    var title = $('#title_doc').val();
    if (title !== '') {
        if(value.length >= 1 && value !== '') {

            var file_data = $("#Document").prop("files")[0];
            var action = 'briefingdoc';
            var form_data = new FormData();

            form_data.append("action", action);
            form_data.append("title", title);
            form_data.append("file", file_data);
            form_data.append("cceveid", <?php echo $_REQUEST['cceveid']; ?>);

            if(selectedValues == '' || selectedValuesPos == '' || selectedValuesPosCat == '') {
                alert('Please select at least one option for each.');
            } else {
                $.ajax({
                   type: "post",
                   url:"pages_ajax/ajax-eventhandbook.php",
                   cache: false,
                   contentType: false,
                   processData: false,
                   data: form_data,
                   success: function(msg) {
                       console.log('done');

                       // this does not work
                       $('#datatable_brief').dataTable({"bDestroy": true});
                   }    
                });
            }
        }
    } else {
        showError(title);
    }
}
</script>
<!--    File Upload      -->

<form name="category_frm" id="category_frm_b" method="post" action="Javascript:void(0)" parsley-validate enctype="multipart/form-data" class="bs-example form-horizontal">
    <div class="form-group">
        <button data-toggle='' id='customuploadhb' data-id="" class='btn btn-default' style="line-height: 1;margin-top: 10px">
          <i class='fa fa-cloud-upload text'></i>
          <span class='text'>Upload</span>
          <i class='fa fa-check text-active'></i>
          <span class='text-active'>Success</span>
        </button>
        <input type="file" id="Document" name="Document" value="<?php if(!empty($Document)) { echo $Document; }?>" placeholder="Add new" class="input-sm form-control data-required" parsley-required="true" >
    </div>
    <button type="button" class="btn btn-white btn-next cust_home event_wizard" data-last="Finish" id="btnnext" onclick="submitNew(event);">Finish</button>
</form>

1 个答案:

答案 0 :(得分:3)

a-ha时刻来得有点迟了 - 我只是发送了包含所有数据属性的新<tr>,并在Ajax成功时使用append()将其作为新行添加到表中。

为我的帖子添加了一个ID - <tbody id="afterajax">

然后将ajax的成功改为:

$.ajax({
 type: "post",
 url:"pages_ajax/core_event/staff_&_volunteer_HQ/ajax-eventhandbook.php",
 cache: false,
 contentType: false,
 processData: false,
 data: form_data,
 success: function(msg) { 
      $("#afterajax").append(msg);
 }
});

但是,当我获得新行时,这些上的.btnView - .btnDelete 点击事件无效。

// Delete
$('.btnDelete').click(function() {
    var id = $(this).attr('data-id');
    deleteRow(id);
});

// View
$('.btnView').click(function() {
    var id = $(this).attr('data-id');
    var docname = $(this).attr('data-docname');
    var title = $(this).attr('data-title');
    var eventaccess = $(this).attr('data-eventaccess');
    var poscataccess = $(this).attr('data-poscataccess');
    var posaccess = $(this).attr('data-posaccess');
    var status = $(this).attr('data-status');
    viewRow(id,docname,title,eventaccess,posaccess,poscataccess,status);
});

所以我改变了它们如下:

// Delete
$(document).off( "click", '.btnDelete' );
$(document).on("click", '.btnDelete', function(event) {
    event.preventDefault();
    var id = $(this).attr('data-id');
    deleteRow(id);
});

// View
$(document).off("click", '.btnView');
$(document).on("click", '.btnView', function() {
    var id = $(this).attr('data-id');
    var docname = $(this).attr('data-docname');
    var title = $(this).attr('data-title');
    var eventaccess = $(this).attr('data-eventaccess');
    var poscataccess = $(this).attr('data-poscataccess');
    var posaccess = $(this).attr('data-posaccess');
    var status = $(this).attr('data-status');
    viewRow(id,docname,title,eventaccess,posaccess,poscataccess,status);
});