2

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.

5
  • Did you used a list of <input type="file"> input in your html? Commented Aug 6, 2017 at 10:43
  • Read up on FormData, you will be able to append your image data to this object, and post via ajax... Commented Aug 6, 2017 at 10:44
  • I tried FormData as well, did not work Commented Aug 6, 2017 at 10:44
  • Paste your html too. Commented Aug 6, 2017 at 10:44
  • Possible duplicate of jQuery Ajax File Upload Commented Aug 6, 2017 at 10:53

4 Answers 4

6

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 ?

Sign up to request clarification or add additional context in comments.

3 Comments

Im basically creating a social media site and this ajax request happenns when i click on post
How do i get the images in the php file when i do this?
The usual way, with $_FILES
1

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(",")

1 Comment

Have you checked performance? Im not shure what happens if youre stringifying a few hundred images ... :/
1

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]);
}

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.