It is not possible to send files to the server along with other data.

HTML:

<input type="file" id='my_file' name="my_file[]" accept='image/*' multiple> 

JS Code:

 // var data = new FormData(); var fp = $("#my_file"); var id= // some value for(var i=0, len=fp[0].files.length; i<len; i++) data.append('my_file[]', fp[0].files[i]); var xmlhttp = getXmlHttp(); xmlhttp.open('POST', '/or/save.php', true); xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlhttp.send("id=" + id + "&" + "data=" + data); 

On the server in save.php I check with print_r($FİLES) . The problem is in the code, on the server all the rules. Where is the mistake?

The following code works, but it is without ajax

  <form method="post" enctype="multipart/form-data" accept='\image'> <input type="file" name="my_file[]" multiple> <input type="submit" value="Upload"> </form> <?php if (isset($_FILES['my_file'])) { $myFile = $_FILES['my_file']; $fileCount = count($myFile["name"]); echo print_r($_FILES); for ($i = 0; $i < $fileCount; $i++) { ?> <p>File #<?= $i+1 ?>:</p> <p> Name: <?= $myFile["name"][$i] ?><br> Temporary file: <?= $myFile["tmp_name"][$i] ?><br> Type: <?= $myFile["type"][$i] ?><br> Size: <?= $myFile["size"][$i] ?><br> Error: <?= $myFile["error"][$i] ?><br> </p> <?php } } ?> 

    2 answers 2

    Your mistake is in this line:

     xmlhttp.send("id=" + id + "&" + "data=" + data); 

    You are trying to send an array of data as a string. It will be correct like this:

     data.append('id', id); xhr.send(data); 

    Full version:

      var data = new FormData(); var fp = document.querySelector('#my_file'); for (var i = 0; i < fp.files.length; i++) { data.append('my_file[]', fp.files[i]); } data.append('id', id); var xhr = new XMLHttpRequest(); xhr.open('POST', '/or/save.php', true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.send(data); 
       var formData = new FormData($('#form')); jQuery.ajax('/endpoint.php', { processData: false, contentType: false, data: formData }); 

      Something like this can

      • I need to simultaneously send files along with other information from other blocks - Tarlan Mamedzadeh
      • so there will be everything, it’s straight the whole form will give way - Serge Esmanovich
      • But other blocks are not in this form - Tarlan Mamedzadeh
      • send 2 forms - Serge Esmanovich
      • In addition, one form of identity is not sent. Did you check your code? - Tarlan Mamedzadeh