Skip to content

Instantly share code, notes, and snippets.

@tokenvolt
Last active December 6, 2016 19:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tokenvolt/6894483 to your computer and use it in GitHub Desktop.
Save tokenvolt/6894483 to your computer and use it in GitHub Desktop.
VanillaJS ajax wrapper.
// http://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery/18078705#18078705
var ajax = {};
ajax.xhr = function() {
try {
return new ActiveXObject('Msxml2.XMLHTTP')
} catch (e1) {
try {
return new ActiveXObject('Microsoft.XMLHTTP')
} catch (e2) {
return new XMLHttpRequest()
}
}
};
ajax.send = function(url, callback, method, data, sync) {
var xhr = ajax.xhr();
xhr.open(method, url, sync);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText)
}
};
if (method == 'POST') {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
xhr.send(data)
};
ajax.get = function(url, data, callback, sync) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url + '?' + query.join('&'), callback, 'GET', null, sync)
};
ajax.post = function(url, data, callback, sync) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url, callback, 'POST', query.join('&'), sync)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment