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