PHP Ajax更新/编辑记录

Can anyone help me on this. I've been working it about 3 days. This is about updating the records. When I update the data, all data's updated except for the the "file". The "file" became empty on the database.

Here is the code for;

EDIT/UPDATE FORM:

<label style="color:#e91e63">Attachement</label>
  <div class="input-group input-group-md">
        <span class="input-group-addon">
            <i class="material-icons">file_upload</i>
        </span>
        <div class="form-line">
            <input type="file" name="files" id="files" required>
        </div>
    </div>

  <!-- Edited Date -->

      <input type="hidden" name="id" id="id" />

  <input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success waves-effect" />


<script>
$(document).ready(function(){
  $('#edit').click(function(){
    $('#insert').val("Insert");
    $('#insert_form')[0].reset();
  });

  $(document).on('click', '.edit_data', function(){
    var id = $(this).attr("id");
    var extension = $('#files').val().split('.').pop().toLowerCase();

    if(extension != '') {
      if(jQuery.inArray(extension, ['gif','png','jpg','jpeg', 'pdf']) == -1) {
        alert("Invalid File");
        $('#files').val('');
        return false;
      }
    }
      $.ajax({
      url:"script/fetch.php",
      method:"POST",
      data:{id:id},
      dataType:"json",
      success:function(data){
        $('#dated').val(data.dated);
        $('#ctrl_no').val(data.ctrl_no);
        $('#title').val(data.title);
        $('#category').val(data.category);
        $('#file').val(data.file);
        $('#fname').val(data.fname);
        $('#adate').val(data.adate);
        $('#createdby').val(data.createdby);
        $('#id').val(data.id);
        $('#insert').val("Update");
        $('#update_Modal').modal('show');
      }
    });
  });

  $('#insert_form').on("submit", function(event){
    event.preventDefault();
      $.ajax({
        url:"script/insert.php",
        method:"POST",
        data:$('#insert_form').serialize(),
        beforeSend:function(){
          $('#insert').val("Inserting");
        },
        success:function(data){
          $('#insert_form')[0].reset();
          $('#update_Modal').modal('hide');
          $('#refresh').html(data);
        }
      });
  });
});
</script>

Fetching the data from the database:

<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "record");
if(isset($_POST["id"]))
{
    $query = "SELECT * FROM dashboard WHERE id = '".$_POST["id"]."'";
    $result = mysqli_query($connect, $query);
    $row = mysqli_fetch_array($result);
    echo json_encode($row);
}
?>

Updating the data.

<?php
$connect = mysqli_connect("localhost", "root", "", "record");
if(!empty($_POST))
{
  $output = '';
  $message = '';

  $ctrl_no = mysqli_real_escape_string($connect, $_POST["ctrl_no"]);
  $title = mysqli_real_escape_string($connect, $_POST["title"]);
  $category = mysqli_real_escape_string($connect, $_POST["category"]);
  $fname = mysqli_real_escape_string($connect, $_POST["fname"]);
  $adate = mysqli_real_escape_string($connect, $_POST["adate"]);
  $createdby = mysqli_real_escape_string($connect, $_POST["createdby"]);

  //file upload

  $file = '';
  if($_FILES["files"]["name"] = '')
  {
    $file = upload_file();
  }
  else
  {
    $file = $_POST["file"];
  }

  if($_POST["id"] != '')
  {
    $query = "
    UPDATE `dashboard`
    SET
    `ctrl_no`='$ctrl_no',
    `title`='$title',
    `category`='$category',
    `file`='$file',
    `fname`='$fname',
    `adate` = '$adate',
    `createdby` = '$createdby'
    WHERE `id`='".$_POST["id"]."'";
    $message = 'Data Updated.';
  }

  if(mysqli_query($connect, $query))
  {
    $output .= "<div class='alert alert-success alert-dismissible'>
    <a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>
    <strong>Success!</strong> $message
    </div>";
    $select_query = "SELECT * FROM `dashboard` ORDER BY `id` DESC";
    $result = mysqli_query($connect, $select_query);
    $output .= '
    <table id="dataTable" style="width:100%" class="table table-bordered table-striped table-hover">
    <thead>
    <tr>
    <th width="6%"><b>Date</b></th>
    <th width="8%"><b>Control No.</b></th>
    <th width="37%"><b>Title / Particular</b></th>
    <th width="17%"><b>Category</b></th>
    <th width="10%"><b>From /<br />End-user</b></th>
    <th width="10%"><b>File</b></th>
    <th width="7%"><b>Action</b></th>
    </tr>
    </thead>
    <tbody>
    ';
    while($row = mysqli_fetch_array($result))
    {
      $output .= '';
    }
    $output .= '</tbody></table>';
  }
  echo $output;
}

function upload_file()
{
    if(isset($_FILES["files"]))
    {
        $extension = explode('.', $_FILES['files']['name']);
        $new_name = rand() . '.' . $extension[1];
        $destination = '../file/' . $new_name;
        move_uploaded_file($_FILES['files']['tmp_name'], $destination);
        return $new_name;
    }
}
?>

<!-- Alert Success -->
<script>
window.setTimeout(function() {
  $(".alert").fadeTo(500, 0).slideUp(500, function(){
    $(this).remove();
  });
}, 5000); //timeout
</script>

The only problem is the file that I can't update. Any ideas? Help is much appreciated. Thanks.

I think ,you are assigning the name of file via input field.if somebody does not assign the value via input filed ,you have used the method upload_file() .so try to change your if with $_POST["file"] = '' which check whether name is assigned or not ,if assigned the used given else used name define in your upload_file().

<?php
$connect = mysqli_connect("localhost", "root", "", "record");
if(!empty($_POST))
{
  $output = '';
  $message = '';

  $ctrl_no = mysqli_real_escape_string($connect, $_POST["ctrl_no"]);
  $title = mysqli_real_escape_string($connect, $_POST["title"]);
  $category = mysqli_real_escape_string($connect, $_POST["category"]);
  $fname = mysqli_real_escape_string($connect, $_POST["fname"]);
  $adate = mysqli_real_escape_string($connect, $_POST["adate"]);
  $createdby = mysqli_real_escape_string($connect, $_POST["createdby"]);

  //file upload

  $file = '';
//make the change here in if
  if($_POST["file"] = '')
  {
    $file = upload_file();
  }
  else
  {
    $file = $_POST["file"];
  }

  if($_POST["id"] != '')
  {
    $query = "
    UPDATE `dashboard`
    SET
    `ctrl_no`='$ctrl_no',
    `title`='$title',
    `category`='$category',
    `file`='$file',
    `fname`='$fname',
    `adate` = '$adate',
    `createdby` = '$createdby'
    WHERE `id`='".$_POST["id"]."'";
    $message = 'Data Updated.';
  }

  if(mysqli_query($connect, $query))
  {
    $output .= "<div class='alert alert-success alert-dismissible'>
    <a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>
    <strong>Success!</strong> $message
    </div>";
    $select_query = "SELECT * FROM `dashboard` ORDER BY `id` DESC";
    $result = mysqli_query($connect, $select_query);
    $output .= '
    <table id="dataTable" style="width:100%" class="table table-bordered table-striped table-hover">
    <thead>
    <tr>
    <th width="6%"><b>Date</b></th>
    <th width="8%"><b>Control No.</b></th>
    <th width="37%"><b>Title / Particular</b></th>
    <th width="17%"><b>Category</b></th>
    <th width="10%"><b>From /<br />End-user</b></th>
    <th width="10%"><b>File</b></th>
    <th width="7%"><b>Action</b></th>
    </tr>
    </thead>
    <tbody>
    ';
    while($row = mysqli_fetch_array($result))
    {
      $output .= '';
    }
    $output .= '</tbody></table>';
  }
  echo $output;
}

function upload_file()
{
    if(isset($_FILES["files"]))
    {
        $extension = explode('.', $_FILES['files']['name']);
        $new_name = rand() . '.' . $extension[1];
        $destination = '../file/' . $new_name;
        move_uploaded_file($_FILES['files']['tmp_name'], $destination);
        return $new_name;
    }
}
?>

<!-- Alert Success -->
<script>
window.setTimeout(function() {
  $(".alert").fadeTo(500, 0).slideUp(500, function(){
    $(this).remove();
  });
}, 5000); //timeout
</script>

Are you sure you get file to server side? if not, you want to pass files as this.(this is example Iam sure you will understand how to fit this to your code). key element is formData :)

var formData = new FormData($("#formid")[0]);
$.ajax({
    url:'url',
    type: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    async: false,
    success:function(response){
        if(response == '100'){
            swal({ 
              title: "Blog Added",
              text: "Blog Added Successfully",
              type: "success",
              confirmButtonText: "OK",
              showCancelButton: false,
            }, function(){
                /*location.reload();*/
                window.location.href = 'redirect link';
            });
        }else{
            toastr.error(response);
        }
    }
}); 

How to pass file data with AJAX and jQuery?