Skip to content

Instantly share code, notes, and snippets.

@gmac
Last active December 17, 2015 15:10
Show Gist options
  • Save gmac/5630172 to your computer and use it in GitHub Desktop.
Save gmac/5630172 to your computer and use it in GitHub Desktop.
API: ajax('url', callbackFunction?, postData?); --> returns: a handle object with an ".abort();" method for canceling the request.
var ajax = (function( root ) {
function getRequest() {
if (root.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');
else if (root.XMLHttpRequest) return new XMLHttpRequest();
else return null;
}
return function(url, callback, post) {
post = post || "";
var req = getRequest();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4 && callback && typeof callback.call == 'function') {
callback(req.responseText);
}
};
if (post) {
req.open("POST", url, true);
req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.setRequestHeader('Connection', 'close');
} else {
req.open("GET", url, true);
}
req.send(post);
}
return !req ? null : {
abort: function() {
req.onreadystatechange = undefined;
req.abort && req.abort();
}
};
};
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment