Skip to content
Advertisement

How do I send files(images) in an array in PHP via ajax?

$('.result').click(function(event) {
        var st = JSON.stringify(fileList);
        $.ajax({
            url: 'mailer.php',
            type: 'POST',
            data: st,
        })
        .done(function(data) {
            console.log(st);
        })
        .fail(function() {
            console.log("error");
        })
        .always(function() {
            console.log("complete");
        });
    });

Mistake https://i.stack.imgur.com/mtsAP.png

However, if you enter just:

console.log(fileList);

It shows everything correctly https://i.stack.imgur.com/kNptA.png

PHP

<?php 
$data = json_decode($_POST['fileList']);
echo $data;

Advertisement

Answer

From the console output in the second image it appears that fileList is an array of File objects. As such you should append them to a FormData object and set that as the data of your $.ajax() call. Try this:

$('.result').click(function(event) {
  var fd = new FormData();
  fileList.forEach(file => fd.append(file.name, file));
  
  $.ajax({
      url: 'mailer.php',
      type: 'POST',
      data: fd,
      contentType: false, // required when sending FormData
      processData: false // required when sending FormData
    }).done(function(data) {
      console.log(data);
    }).fail(function() {
      console.log("error");
    }).always(function() {
      console.log("complete");
    });
});

From there you will need to use the $_FILES collection in PHP to access the files sent in the request, not $_POST.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement