0

I have a form tha have selects, checkboxes and a file upload. The code below works for the data, but when I print "$_FILES" in my target php file it gives me an empty array. The following code works only for data:

$('form.ajax').on('submit', function () {
    event.preventDefault();

    // Update button text.
    var uploadButton = document.getElementById('submit');
    uploadButton.innerHTML = 'Uploading...';
    var that = $(this),
        url = that.attr('action'),
        type = that.attr('method'),
        data = {}

    that.find('[name]').each(function (index, value) {
        var that = $(this),
            name = that.attr('name'),
            value = that.val();

        data[name] = value;
    });

    $.ajax({
        url: url,
        type: type,
        data: data,
        success: function (response) {
            console.log(response);
        }
    });
    return false;
});

And the next part works only for files:

$('form.ajax').on('submit', function () {
    event.preventDefault();

    // Update button text.
    var uploadButton = document.getElementById('submit');
    uploadButton.innerHTML = 'Uploading...';

    var that = $(this),
        url = that.attr('action'),
        type = that.attr('method'),
        data = new FormData();
    var element = document.getElementById("fileupload");
    var myfiles = element.files;
    var data = new FormData();
    var i = 0;
    for (i = 0; i < myfiles.length; i++) {
        data.append('file' + i, myfiles[i]);
    }

    $.ajax({
        url: url,
        type: type,
        contentType: false,
        data: data,
        cache: false,
        processData: false,
        success: function (response) {
            console.log(response);
        }
    });
    return false;
});

For what I've noticed the lines contentType: false and processData: false seem to make the $_POST array return empty. Is there a way to combine this to have the data in $_POST and the file in $_FILES using the same code?

Thanks

Rajan Goswami
  • 769
  • 1
  • 5
  • 17
Erick Skrobot
  • 189
  • 4
  • 22
  • In the latter you should provide the `form` DOMElement to the `FormData` constructor. That will give you all fields' data and the files. See the answer I marked as duplicate for more information. – Rory McCrossan Nov 16 '15 at 13:03
  • Although I don't believe this is a duplicate question, I agree the answer can be found in the question marked with some guidance. If anyone has the same problem, the fix was to change data = new FormData() for data = new FormData($('form')[0]. Thanks for the reply. – Erick Skrobot Nov 16 '15 at 13:25

0 Answers0