Skip to content

Instantly share code, notes, and snippets.

@zeusbaba
Last active November 21, 2017 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeusbaba/fb165397b5ecf75e57062868a8c08829 to your computer and use it in GitHub Desktop.
Save zeusbaba/fb165397b5ecf75e57062868a8c08829 to your computer and use it in GitHub Desktop.
Post-on-load
window.onload = function () {
postJsonData().then(function (theResult) {
console.log("theResult: " + theResult);
// do something else if necessary
});
}
function getJsonData() {
targetUrl = "https://api.etcetc.com/gooo";
return new Promise(function (resolve, reject) {
var request = new XMLHttpRequest();
request.open("GET", targetUrl, true);
request.setRequestHeader("content-type", "application/json");
request.send(null);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
var respJson = JSON.parse(request.responseText);
resolve(respJson);
}
}
} // onreadystatechange
});
} // var myJsonData
function postJsonData() {
targetUrl = "https://api.etcetc.com/gooo";
var xhr = new XMLHttpRequest();
xhr.open("POST", targetUrl, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
// body data to post
var data = JSON.stringify({"key1": "val1", "key2": "val2"});
xhr.send(data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment