Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save S204STi/221c7b72641b1ef4ee5cd796fd4aed74 to your computer and use it in GitHub Desktop.
Save S204STi/221c7b72641b1ef4ee5cd796fd4aed74 to your computer and use it in GitHub Desktop.
AJAX wrapper for XMLHttpRequest supporting GET and POST
/*
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