Search code examples
phpjqueryajaxfile-uploadslim

FormData not passed to PHP via Ajax request


I'm after such flow:

  1. user selects the file(s)
  2. Ajax request(s) are fire up to the PHP backend
  3. Photo processing
  4. Output on the screen.

I am stuck on the step 2. For some reason, my PHP does not get the File object.

Here is my code.

a simple form with a div#uploadZone pretending drop zone for user's files.

// file selected
$("#files").change(function() {
  for (var index = 0; index < $('#files')[0].files.length; index++) {
    var fd = new FormData();
    fd.append('file', $('#files')[0].files[index]);
    fd.append('item', $('#record').val());
    // formData for console output
    console.table([...fd]);
    $(document).uploadPhoto($('#files')[0].files.length - 1, index, [...fd]);
  }
});

(function($) {
  $.fn.uploadPhoto = function(count, loopIndex, formData) {
    var index = loopIndex;
    var total = count;
    $.ajax({
      url: "/ajax/photo/new",
      method: "post",
      data: formData,
      cache: false,
      contentType: false,
      processData: false,
    }).done(function(msg) {
      // show uploaded photos
      console.log('OK');
    }).fail(function(jqXHR, msg) {
      console.log('ERROR');
    });
  }
}(jQuery));
<form action="/photo/new" id="uploadDataForm" method="post" enctype="multipart/form-data">
  <fieldset class="pb-5">
    <div class="text-center p-4 idle" id="uploadZone">Drag & drop here</div>
    <input class="d-none" type="file" name="file" id="file">
    <div class="mt-4 pt-2 d-flex flex-wrap align-items-stretch" id="gallery-wrapper"></div>
    <input type="file " id="files " name="files[] " multiple>
    <input type="hidden " id="record " name="record " value="a1 ">
  </fieldset>
</form>

When looking at the console, the result of console.table([...fd]) is:

| Index | 0    | 1  |
|-------|------|----|
| 0     |'file'|File|
| 1     |'item'|'a1'|

By expanding the details of the entry under [0] index, I'm able to see File meta data, i.e.:

  • lastModified: 1685604952446
  • lastModifiedDate: Thu Jun 01 2023 09:35:52 GMT+0200
  • name: "ef876689-004e-11ee-8b7f-c03ebabf9acb.jpg"
  • size: 5410
  • type: "image/jpeg"
  • webkitRelativePath: ""

However, when I inspect data on PHP:

// Slim4 framework

$uploadedFiles = $request->getUploadedFiles();
$this->logger->debug(var_dump($uploadedFiles));

// or like this
var_dump($_FILES));

Both outputs: null

I have no idea why output is null. Any ideas mates? I'm going crazy with this.


Solution

  • You have an error in your code, pass the FormData to your uploadPhoto properly. Also delete spaces from your HTML attributes otherwise the JS code wouldn't work at all (On the other hand the OP was able to POST. so probably spaces are just wrong example data):

    $(document).uploadPhoto($('#files')[0].files.length - 1, index, fd);
    

    enter image description here Otherwise you have a wrong form payload: enter image description here