Shreyas Sreenivas
Shreyas Sreenivas

Reputation: 351

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.

Upvotes: 2

Views: 15642

Answers (4)

A. El-zahaby
A. El-zahaby

Reputation: 1160

you can just use the list symbol after the input name [i]

for example:

let formData = new FormData();

let files = fileInput.prop('files');
for (let i = 0; i < TotalFiles; i++) {
    formData.append('file['+i+']', files[i]);
}

Upvotes: 1

Ataur Rahman Munna
Ataur Rahman Munna

Reputation: 3917

Use FormData Object to send files using ajax.new FormData($('#your_form_id')[0]) automatically appends all form input in FormData object which we can be done by manually formData.append('file1',file1);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
let formData = new FormData($('#your_form_id')[0]);
    $.ajax({
        url: 'PHP/posts.php',
        type: 'POST',
        data: formData,
        dataType:'json',
        processData: false,
        contentType: false,
        success: function(response) {
            console.log(response);
            location.reload();
        },
        error: function() {
            console.log('fail');
        }
    });
</script>

Upvotes: 0

Tushar Gupta
Tushar Gupta

Reputation: 15913

You can pass a JSON object to PHP, which would be the convenient solution here

var data ={'image1':image1,'image2':image2};

You can pass this object to the php code and then parse it:

Pass the object as a string:

AJAX call:

$.ajax({
    type    : 'POST',
    url     : 'PHP/posts.php',
    data    : {result:JSON.stringify(data)},
    success : function(response) {
        alert(response);
    }    
});

You can handle the data passed to the result.php as :

$data    = $_POST["result"];
$data    = json_decode("$data", true);

//just echo an item in the array
echo "image1 : ".$data["image1"];

Another option would be serializing the array before sending, or convert it into a comma separated string using array.join, then parse/split on the posts.php

 array.join(",")

Upvotes: 1

adeneo
adeneo

Reputation: 318182

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 ?

Upvotes: 6

Related Questions