Created
November 3, 2015 10:32
-
-
Save christophengelmayer/df2e960ffe238999ddb5 to your computer and use it in GitHub Desktop.
Vanilla JavaScript AJAX Function
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
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