Skip to content

Instantly share code, notes, and snippets.

@nitschmann
Created July 21, 2014 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nitschmann/cd9e1b8e04af977005f8 to your computer and use it in GitHub Desktop.
Save nitschmann/cd9e1b8e04af977005f8 to your computer and use it in GitHub Desktop.
Basic ajax handler function in JavaScript without jQuery
function ajax(url, method, data, async) {
method = typeof method !== 'undefined' ? method : 'GET';
async = typeof async !== 'undefined' ? async : false;
if (window.XMLHttpRequest) {
var xhReq = new XMLHttpRequest();
}
else {
var xhReq = new ActiveXObject('Microsoft.XMLHTTP');
}
if(typeof data != 'string') {
var query = [];
for(var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
data = query.join('&');
}
if(method == 'POST') {
xhReq.open(method, url, async);
xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest");
if(async === true && xhReq.readyState === 4 && xhReq.status === 200) {
callback(xhReq);
}
xhReq.send(data);
}
else {
if(typeof data !== 'undefined' && data !== null) {
url = url+'?'+data;
}
xhReq.open(method, url, async);
xhReq.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhReq.send(null);
if(method == 'GET') {
return xhReq.responseText;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment