Skip to content

Instantly share code, notes, and snippets.

@james-jlo-long
Created May 15, 2018 09:53
Show Gist options
  • Save james-jlo-long/bb79d87e98bec6be7213f545633e5c14 to your computer and use it in GitHub Desktop.
Save james-jlo-long/bb79d87e98bec6be7213f545633e5c14 to your computer and use it in GitHub Desktop.
A simple function for posting data
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