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

Erick Skrobot
  • 189
  • 4
  • 22
  • Ajax file upload is a mess, you should take care of MIME type, chunks, file permissions, etc. I would point on a ready component like https://github.com/blueimp/jQuery-File-Upload or http://www.plupload.com/ – Mat Nov 13 '15 at 16:53
  • Why someone marks a question as duplicate and don't even bother to give soma guidance about how the answer should look like? That doesn't help at all. – Erick Skrobot Nov 16 '15 at 13:28
  • Found the answer, the fix was to change data = new FormData() for data = new FormData($('form')[0]) – Erick Skrobot Nov 16 '15 at 13:29

0 Answers0