Last active
April 3, 2018 12:55
-
-
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
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
// 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