Last active
August 29, 2015 14:04
-
-
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.
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
/* | |
* 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