Skip to content

Instantly share code, notes, and snippets.

@Julian-Nash
Last active April 3, 2018 12:55
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 Julian-Nash/5bb7ee55aab15386e6d39606ca7a9679 to your computer and use it in GitHub Desktop.
Save Julian-Nash/5bb7ee55aab15386e6d39606ca7a9679 to your computer and use it in GitHub Desktop.
Get form data on click and send json obj to server in fetch post. ES5 & ES6
// ES6
document.getElementById("post_btn").addEventListener("click", (e) => {
e.preventDefault();
let user_credentials = {
first_name: document.getElementById("first_name").value,
last_name: document.getElementById("last_name").value,
};
fetch("http://127.0.0.1:5000/testing_fetch", {
method: "POST",
credentials: "include",
body: JSON.stringify(user_credentials),
cache: "no-cache",
headers: new Headers({"content-type": "application/json"})
})
.then(response => {
if (response.status !== 200){
console.log(`Looks like there was a problem. Status code: ${response.status}`);
return;
}
response.json()
.then(data => {
console.log(data)
});
})
.catch(error => {
console.log(`Fetch error: ${error}`);
});
}); // end
// ------------------------------------------------------------------------------------------------------------------------------ //
// ES5
"use strict";
document.getElementById("post_btn").addEventListener("click", function(e) {
e.preventDefault();
var user_credentials = {
first_name: document.getElementById("first_name").value,
last_name: document.getElementById("last_name").value,
};
fetch("http://127.0.0.1:5000/testing_fetch", {
method: "POST",
credentials: "include",
body: JSON.stringify(user_credentials),
cache: "no-cache",
headers: new Headers({ "content-type": "application/json" })
})
.then(function(response) {
if (response.status !== 200) {
console.log(
"Looks like there was a problem. Status code: " + response.status
);
return;
}
response.json().then(function(data) {
console.log(data);
});
})
.catch(function(error) {
console.log("Fetch error: " + error);
});
}); // end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment