0

How do I append imageList[] array to FormData?

<form id="myform" method="POST" enctype="multipart/form-data">   
<input id="imageupload" type="file" name="file[]" onchange="preview_image()" 
 multiple/>
<input id="send" type="submit" name="submit" value="Upload" />

<script>
function preview_image() {
     var imagesArray = event.target.files;
     var imageList = [];

var total_file=document.getElementById("imageupload").files.length;
for(var i=0;i<total_file;i++)
{
   $('#demo').append("<img id='pre' alt='image' 
   src='"+URL.createObjectURL(imagesArray[i])+"'><button 
   id='del2'>Delete</button>");
   imageList.push(imagesArray[i]);    
}
  window.imageList = imageList;
}

$(document).ready(function(){
$("#myform").on('submit',function(event){
 event.preventDefault();


 var formdata = new FormData();
 formdata.append(imageList[]);

 $.ajax({
            url:'upload.php',
            type: 'POST',
            contentType: false,
            processData: false, 
            data: formdata,
             success : function(data){

             }
 });
 });
 });

 </script>

I have created a var imageList array so that I could manipulate the array because is read-only. I would like to send the files from my imageList array using AJAX which is using FormData() .

ticktock
  • 151
  • 1
  • 12
  • Possible duplicate [appending array to FormData and send via AJAX](https://stackoverflow.com/questions/16104078/appending-array-to-formdata-and-send-via-ajax) – Mohamed-Yousef Jun 11 '17 at 21:34
  • I'm not sure how to access the "key","value" pair from my function in order to JSON.stringify. imagesArray and [i] are not global variables. In the given example as "Possible duplicate" files are accessed by document.getElementById('files'). – ticktock Jun 11 '17 at 21:44
  • The question is, why didn't you make `imageList` a formData object to begin with ? – adeneo Jun 11 '17 at 21:46
  • Because I have a delete function and the files in the array that are not deleted are to be submitted. – ticktock Jun 11 '17 at 21:56

0 Answers0