Last active
May 22, 2016 21:04
-
-
Save loganking/4be8161ea628fba57437f490c22e2b39 to your computer and use it in GitHub Desktop.
AJAX wrapper for XMLHttpRequest supporting GET and POST
This file contains 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
/* | |
data (optional) - a JSON string to send with the request | |
*/ | |
function ajax(method, url, handler, data) { | |
var xhr = new XMLHttpRequest(); | |
xhr.onreadystatechange = function(){ | |
if (this.readyState === 4) { | |
if (this.status === 200) { | |
handler(null, JSON.parse(this.responseText)); | |
} else { | |
handler(this.statuscode, null); | |
} | |
} | |
} | |
xhr.open(method, url); | |
if (method === 'POST') { | |
xhr.setRequestHeader("Content-type", "application/json"); | |
xhr.setRequestHeader("Content-length", data.length); | |
xhr.setRequestHeader("Connection", "close"); | |
xhr.send(data); | |
} else { | |
xhr.send(); | |
} | |
} | |
ajax('POST', 'https://secure-eyrie-78012.herokuapp.com/users', function(err, data){ | |
console.log(data); | |
}, JSON.stringify({firstName: "Kyle", lastName: "Coberly", role: 1})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment