Skip to content

Instantly share code, notes, and snippets.

@teckliew
Last active August 29, 2015 14:23
Show Gist options
  • Save teckliew/af710e1ce3322c7df284 to your computer and use it in GitHub Desktop.
Save teckliew/af710e1ce3322c7df284 to your computer and use it in GitHub Desktop.
AJAX function with without jQuery. JS only.
var ajax = {
load : function() {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
},
otherMethod : someFunction() {
// paste here
}
}
ajax.load();
// example call. Our simplified "load" function accepts a URL and CALLBACK parameter.
ajax.load('test.txt', function(xhr) {
document.getElementById('container').innerHTML = xhr.responseText;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment