Okay, so all in all, I'm trying to upload a single file via ajax using FormData and a CakePHP form. The problem is that trying to catch the data by error logging the $this->request->data in the controller returns an empty files array.
So, I've set up my form, using CakePHP's helper. But the structure of that isn't really relevant. The javascript used will output whatever debugging we need.
So here's the setup. I have a controller called RequestsController and my view name/function is upload_files.
The piece of javascript code looks like this. A note, this is called when the value of the file input element changes (i.e once they've selected a file to upload)
plugin.fileUpload = function(el)
{
el = $(el);
form = el.closest('form');
var files = el.get(0).files;
console.log(files.length)
var formData = new FormData();
for (var i = 0; i < files.length; i++)
{
var file = files[i];
console.log(file);
formData.append('files[]', file, file.name);
}
formData.append("username", "[email protected]");
var xhr = new XMLHttpRequest();
xhr.open('POST', form.attr('action'), true);
xhr.onload = function () {
if (xhr.status === 200) {
toastr.success('Successfully loaded');
}
else
{
alert('An error occurred!');
}
};
xhr.send(formData);
console.log(files);
console.log(formData);
}
Excuse all the console logs. It's for the purpose of showing the output and debugging.
You'll see I also append a username field just to test that the post was making it with some data intact to the controller. It is indeed. Here's the output from logging the $this->request->data array:
2014-06-18 17:51:41 Error: RequestsController::upload_files - Line 45
2014-06-18 17:51:41 Error: Array
(
[username] => [email protected]
)
As you can see, username field goes through but not the files.
I've also logged the files variables in JS to the console and it looks great. In Firebug it looks like this:
FileList { 0=File, length=1, item=item(), more...}
Logging the the FormData variable to the console looks like this:
FormData { append=append()}
Sigh, nothing in the FormData output suggests that the files are making it to the FormData object.
Any ideas??