Skip to content

Instantly share code, notes, and snippets.

@christophengelmayer
Created November 3, 2015 10:32
Show Gist options
  • Save christophengelmayer/df2e960ffe238999ddb5 to your computer and use it in GitHub Desktop.
Save christophengelmayer/df2e960ffe238999ddb5 to your computer and use it in GitHub Desktop.
Vanilla JavaScript AJAX Function
var ajax = (function () {
var ajax = {};
ajax.get = function (url, callbackFunc) {
var req = prepareRequest('GET', url, callbackFunc);
req.send();
}
ajax.post = function (url, params, callbackFunc) {
var req = prepareRequest('POST', url, callbackFunc);
req.send(params); //e.g. "firstname=John&lastname=Doe"
}
function prepareRequest(method, url, callbackFunc) {
var req = new XMLHttpRequest();
req.open(method, url, true);
req.onreadystatechange = function () {
if (req.readyState != 4 || req.status != 200) return;
callbackFunc(req);
};
if(method == 'POST') r.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
return req;
}
return ajax;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment