Created
July 21, 2014 10:33
-
-
Save nitschmann/cd9e1b8e04af977005f8 to your computer and use it in GitHub Desktop.
Basic ajax handler function in JavaScript without jQuery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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