Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send array of files using AJAX

Say I have an array which contains a few images:

var images = [image1, image2, image3]

How do I send these images to a php file using AJAX in a single request?

The following code did not work:

$.ajax({
    url: 'PHP/posts.php',
    type: 'post',
    data: {data: images},
    success: function(data) {
      alert(data);
      location.reload();
    }
  });

My HTML:

<div id="newPostFile">
    <label for="newPostFiles"><i class="fa fa-file-text-o" id="newPostFileIcon" aria-hidden="true"></i></label>
    <input type="file" name="newPostFiles" id="newPostFiles">
</div>

Endgoal: Whenever a file is selected, the file is added to the array and when the submit button is clicked, all the files are uploaded at once.

like image 913
Shreyas Sreenivas Avatar asked Dec 11 '25 17:12

Shreyas Sreenivas


1 Answers

You have to send files as formData

var images = [image1, image2, image3]
var data   = new FormData();

images.forEach(function(image, i) {
    data.append('image_' + i, image);
});

$.ajax({
    url: 'PHP/posts.php',
    type: 'post',
    data: data,
    contentType: false,
    processData: false,
    success: function(data) {
       console.log(data);
       location.reload();
    }
});

But as you're reloading the page anyway, why use ajax at all ?

like image 130
adeneo Avatar answered Dec 13 '25 07:12

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!