简体   繁体   中英

files do not post when javascript submits form

I have an image upload form which is submitted by a javascript but the file data is not being submitted. I have looked at examples of how to fix this with ajax but cannot find any examples that address it with the javascript submit that I am using.

<td>New Photo<br>
<div id="editphoto">
<form id="editphoto" enctype="multipart/form-data"  method="post" action="editphoto.php">
<input type="hidden" name="employeeid" value="<?php echo $listing[$k]["employeeid"] ?>">
<input type="file" name="file2">
<input type="submit" value="Submit">
</form></div></td>

<script>
     $('#editphoto form').submit(function(){
          var data=$(this).serialize();
          $.post('editphoto.php', data , function(returnData){
                      $('#editphoto').html( returnData)
          })

          return false; // stops browser from doing default submit process
    });
      </script>

Files cannot be serialized. You can use FormData To submit a file using jQuery.

 $('#editphoto form').submit(function(){

    var formData = new FormData();
    formData.append('file2', $('input[type=file]')[0].files[0]);

    // append other form-data to formData object
    var otherData = $(this).serialize();
    $.each( otherData , function(key, field){
      formData.append(field.name, field.value);
    });

    // post form
    $.ajax({
      url: 'editphoto.php',
      data: formData,
      processData: false,
      contentType: false,
      type: 'POST',
      success: function( returnData ) {
          $('#editphoto').html( returnData)
      }
    }); 

    return false; // stops browser from doing default submit process
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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