Skip to content

Instantly share code, notes, and snippets.

@krrishd
Last active August 29, 2015 14:04
Show Gist options
  • Save krrishd/c4b152d47d60335b2311 to your computer and use it in GitHub Desktop.
Save krrishd/c4b152d47d60335b2311 to your computer and use it in GitHub Desktop.
For when I don't want to use jQuery or Angular to do a trivial POST HTTP request, neither do I care for raw XHR.
/*
* By Krish Dholakiya (itskrish.co, git.io/krish)
* MIT Licensed.
*
* POST('http://example.com', {'keyOne': 'valueOne', 'keyTwo': 'valueTwo'}, function(response) {
* var responseFromServer = response;
* });
*
* TODO: use some sort of promise rather than callbacks
*/
window.POST = function (url, data, callback) {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
var params = "";
var loaded = false;
var keys = Object.keys;
keys(data).forEach(function(d) {
if(params.length<1) {
params = params + d + '=' + data[d];
} else {
params = params + '&' + d + '=' + data[d];
}
});
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.addEventListener('load', function(e) {
if(callback) {
callback(xhr.responseText);
} else {
return xhr.responseText;
}
}, false);
xhr.send(params);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment