If you want your code to work in old browsers, put this in the
of your HTML document:
Replace /path/to/promise/polyfill.js with the path to your Promise polyfill. This will create a Promise class if the class is not already native and allow your code to run on old browsers such as Internet Explorer. Internet Explorer and other old browsers make up a small minority of the market share which might seem insignificant, but this still translates to millions of users so I do not recommend totally dismissing these users.
May I suggest this Promise polyfill:
https://github.com/taylorhakes/promise-polyfill
Now you have access to the Promise class.
If you want your code to work in really old browsers like IE 6-8 you need to use onreadystatechange instead of onload. There is no harm in this as onreadystatechange remains in use in all current browsers for backwards compatibility:
function send_request(xhr, data) {
var p, s = '', promise = new Promise(function (resolve, reject) {
xhr.onreadystatechange = function() {
if(xhr.readyState==4) {
resolve(xhr);
}
}
xhr.onerror = function() {
reject("error");
}
});
if (data && data.constructor==Object) {// serialize object
for (p in data) if (data.hasOwnProperty(p)) {
if (s) s+="&";
s+= encodeURIComponent(p)+"="+encodeURIComponent(data[p]);
}
data = s;
}
xhr.send(data);
return promise
}
xhr = new XMLHttpRequest();
xhr.open("GET", "/some/file", true);
send_request(xhr).then(function(xhr) {
if (xhr.status>=200 || xhr.status<400) {
//success
}
else {
return Promise.reject(xhr.statusText);
}
}).catch(function(msg) {
//fail
});
Keep in mind that IE 6 does not support XMLHttpRequest so you would need to polyfill that as well which you can do with ActiveX. Something like the following in your document
might work: