Skip to content
Advertisement

How to pass an image file thru jquery $.ajax() correctly?

I am trying to upload an image and passing the userID and file through ajax to the PHP file profileSettings.inc.php. However it succeed in running the php file, but the data was not passed through. When I ran print_r($_POST);, in the php file it returned an empty array.

    $(document).ready(function(){
  $("form#profileForm").submit(function(event){
    event.preventDefault();
    var file = $("#file")[0].files[0];
    var userID = $("input[type=hidden][name=userID]").val();
    var uploadProfileSubmit = $('button[name=uploadProfileSubmit]').val();

    $.ajax({
      url: 'includes/profileSettings.inc.php',
      data: {userID: userID, file: file, uploadProfileSubmit: uploadProfileSubmit},
      processData: false,
      contentType: false,
      type: 'POST'
      }).done(function(data){
        $("#settings-msg").html(data);
        alert(data);
    });
  });
});

Form:

<form id="profileForm" class="profileForm" method="post" action="includes/profileSettings.inc.php" enctype='multipart/form-data'>
        <input type="hidden" name="userID" id="userID" value="<?php echo $userID ?>">
        <h2>Profile</h2>
        <hr>
        <div class="row">
          <div class="col-sm-7">
            <div class="row w-100 p-2">
              <label for="file" class="form-label font-weight-bold h6">Profile Image</label> <br>
              <span>Images must be in an .jpg, .jpeg, and .png format. All profile images will be resized to 400x400 pixels. No copyrighted or NSFW images allowed. </span>
              <input type="file" name="file" class="form-control file"  id="file">
              <div id="imgFeedback" class="invalid-feedback"></div>
              <button class="btn btn-primary" type="submit" id="uploadProfileSubmit" name="uploadProfileSubmit">Submit</button>
            </div>
            <div class="row w-100 p-2">
              <label for="file" class="form-label font-weight-bold h6">Remove Image</label> <br>
              <span>You can remove this picture by clicking the button below. You will be given an default picture as your profile, unless a new image is submitted.</span>
              <button class="btn btn-primary" type="submit" id="deleteProfileSubmit" name="deleteProfileSubmit">Remove</button>
            </div>
          </div>
        </div>
      </form> 

profileSettings.inc.php:

<?php
print_r($_POST);
if(isset($_POST["uploadProfileSubmit"])){
    $userID = $_POST['userID'];
    $file = $_FILES['file'];

    require $_SERVER['DOCUMENT_ROOT'].'/config/dbh.inc.php';
    require $_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php';

    $uploadError = false;
    if(!empty($file['name']) && !empty($file['type']) && $file['size'] != 0){
        $errorFile = incorrectImgFile($file);
        if($errorFile !== false){
            $uploadError = true;
            $errorMsg = $errorFile;
        } else {
            moveFile($file);
            $imgName = $file['name'];
        }
    }else {
        $imgName = imgNameDB($conn, $userID);
    }

    if($uploadError !== true){
        //updateProfileImg($conn, $userID, $imgName)
        echo "success";
    }

 } else {
    echo "failed?";
 }

?>

Anyone knows what I am doing wrong in passing the data through ajax. Thanks in advance!

UPDATED: As suggested to use FormData, I updated the javascript code as followed:

  $("form#profileForm").submit(function(event){
    event.preventDefault();
    var formData = new FormData($("form#profileForm")[0]);
    var file = $("form#profileForm")[0].files;
    var userID = $("input[type=hidden][name=userID]").val();
    var uploadProfileSubmit = $('button[name=uploadProfileSubmit]').val();
    var formData = new FormData();
    formData.append("file", file);
    formData.append("userID", userID);
    formData.append("uploadProfileSubmit", uploadProfileSubmit);
    $.ajax({
      url: 'includes/profileSettings.inc.php',
      data: formData,
      processData: false,
      contentType: false,
      enctype: 'multipart/form-data',
      type: 'POST'
      }).done(function(data){
        $("#settings-msg").html(data);
        alert(data);
    });
  });

Feb 03 2021 UPDATE: When using formData, $_FILES['file'] doesn’t exist, but $_POST['file'] does and [file] is undefined. How do I pass the file so I can grab the data using $_FILES['file'] in php server side?

Advertisement

Answer

just use data : new FormData(this) and it will automatically pass all the values alongside $_POST and $_FILES

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement