Created
May 15, 2018 09:53
-
-
Save james-jlo-long/bb79d87e98bec6be7213f545633e5c14 to your computer and use it in GitHub Desktop.
A simple function for posting data
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
function post(url, data) { | |
return new Promise(function (resolve, reject) { | |
var xhr = new XMLHttpRequest(); | |
var params = new URLSearchParams(); | |
Object.entries(data).forEach(function (pair) { | |
params.set(pair[0], pair[1]); | |
}); | |
xhr.open("POST", url, true); | |
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); | |
xhr.onreadystatechange = function () { | |
if ( | |
( | |
xhr.readyState === XMLHttpRequest.DONE | |
|| xhr.readyState === "complete" | |
) | |
&& xhr.status === 200 | |
) { | |
resolve(xhr.responseText, xhr); | |
} | |
}; | |
xhr.onerror = function () { | |
reject(xhr); | |
}; | |
xhr.send(params.toString()); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment