0

I'm unable to get the correct syntax for adding a file (or multiple files) when scanning all elements from a <form>. The problematic line is data.append("PhotosToUpload", TheFile);. I've tried many different ways but no success.

A minimum code example follows.

function SendData() {
  var inputs = document.getElementById("MyForm").elements;

  var xhr = new XMLHttpRequest();
  xhr.open('post', 'TheHandler.php', true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      document.getElementById("TheResponse").innerHTML = xhr.responseText;
    }
  }

  var data = new FormData;
  for (i = 0; i < inputs.length; i++) {
    if (inputs[i].type === 'file') {
      if (inputs[i].files.length != 0) {
        for (a = 0; a < inputs[i].files.length; a++) {
          var TheFile = inputs[i].files[a];

          ///////// HERE MY PROBLEM ////////////

          data.append("PhotosToUpload", TheFile);
          //For multiple files also I tried:
          //data.append("PhotosToUpload[]", TheFile);
        }
      }
    } else {
      var TheName = inputs[i].name;
      var TheValue = inputs[i].value;
      data.append(TheName, TheValue);
    }
  }
  xhr.send(data);
  return false;
}
<form id="MyForm" onsubmit="event.preventDefault(); SendData();">
  <div>Order<input type="text" name="Order" value=""></div>
  <div>SubOrder<input type="text" name="SubOrder" value=""></div>
  <div>Select photo (.jpg) to Upload: <input type="file" name="PhotoToUpload" id="PhotoToUpload" multiple size="3"></div>
  <input type="submit" name="SendD" id="SendD" value="Send data" >
</form>

<div id="TheResponse"></div>
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
CMArg
  • 1,525
  • 3
  • 13
  • 28

1 Answers1

3

You're overcomplicating things. You don't need to think about the individual elements at all. Just give the FormData object your form and let it take care of finding the data in it.

var form = document.getElementById("MyForm");
var data = new FormData(form);
xhr.send(data);

Note that PHP requires special naming conventions when you have multiple values for the same field name.

name="PhotoToUpload" needs to be name="PhotoToUpload[]"

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1) Its incredible simple for adding form elements...! 2) I can't get the file sent. If in `TheHandler.php` I wrote `foreach($_POST as $key=>$value){echo $key."-".$value."
    ";}` only Order and SubOrder are printed (i.e., there is no `PhotoToUpload`).
    – CMArg May 02 '18 at 15:53
  • @CMArg — PHP puts file uploads in `$_FILES`, not `$_POST`. – Quentin May 02 '18 at 16:14
  • I'm still newbie... You're right, Thanks a lot. – CMArg May 02 '18 at 16:17