I'm having trouble incorporating file upload support into my AJAX post function. Can anyone provide some guidance on what I might be missing?
function ajax_post(url, param) {
if (url.substr(0, 11) == 'javascript:') {
result = 'Error: form submits to JavaScript function.\n\nFunction cannot be processed when passed off by the onsubmit event handler.';
} else {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {}
}
}
if (!xhr) {
var result = 'Error: your browser does not support AJAX.';
browser_upgrade_notice();
} else {
xhr.open('POST', url, true);
var f = document.getElementById(id_page).getElementsByTagName('form');
for (var i = 0; i < f.length; i++) {
if (f[i].compareDocumentPosition(option.submit) == 20) {
f = f[i];
break;
}
}
var i = f.getElementsByTagName('input');
var k = 0;
for (var j = 0; j < i.length; j++) {
if (i[j].type == 'file') {
k++;
break;
}
}
if (k == 0) {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(param);
} else {
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
var fd = new FormData();
var z = param.split('&');
for (var j = 0; j < z.length; j++) {
var y = z[j].split('=');
fd.append(y[0], y[1]);
}
for (var j = 0; j < i.length; j++) {
if (i[j].type == 'file') {
fd.append('file_' + j, i[j].files[0]);
}
}
xhr.send(fd);
}
if (xhr.readyState == 4) {
var result = xhr.responseText;
}
}
}
return result;
}