For AJAX requests, you cannot really use .serialize()
functions. You need to use FormData()
. You can also put a progress bar. We need to check for the support first:
function supportAjaxUploadWithProgress() {
return supportFileAPI() && supportAjaxUploadProgressEvents() && supportFormData();
function supportFileAPI() {
var fi = document.createElement('INPUT');
fi.type = 'file';
return 'files' in fi;
};
function supportAjaxUploadProgressEvents() {
var xhr = new XMLHttpRequest();
return !! (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload));
};
function supportFormData() {
return !! window.FormData;
}
}
The next step is to submit the form using AJAX:
var form = document.getElementById('form-id');
var formData = new FormData(form);
You have to have these HTML:
var form = document.getElementById('the-form');
form.onsubmit = function() {
var formData = new FormData(form);
formData.append('file', file);
var xhr = new XMLHttpRequest();
// Add any event handlers here...
xhr.open('POST', form.getAttribute('action'), true);
xhr.send(formData);
return false; // To avoid actual submission of the form
}
<form id="the-form" action="/upload/path" enctype="multipart/form-data">
<input name="file" type="file">
<input type="submit" value="Upload" />
</form>
More info: Ridiculously simple Ajax uploads with FormData.