Last active
May 4, 2019 19:17
-
-
Save seamusleahy/e63911a939f73ec8588bd472ed07980d to your computer and use it in GitHub Desktop.
Using the Fetch HTML5 API to POST a form and get back JSON 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
// 3. Use the response | |
// ================================ | |
responsePromise | |
// 3.1 Convert the response into JSON-JS object. | |
.then(function(response) { | |
return response.json(); | |
}) | |
// 3.2 Do something with the JSON data | |
.then(function(jsonData) { | |
console.log(jsonData); | |
document.getElementById('results').innerText = | |
JSON.stringify(jsonData); | |
}); |
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
// 2. Make the request | |
// ================================ | |
var url = '/echo/json/'; | |
var fetchOptions = { | |
method: 'POST', | |
headers, | |
body: formData | |
}; | |
var responsePromise = fetch(url, fetchOptions); |
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
// 1. Setup the request | |
// ================================ | |
// 1.1 Headers | |
var headers = new Headers(); | |
// Tell the server we want JSON back | |
headers.set('Accept', 'application/json'); | |
// 1.2 Form Data | |
// We need to properly format the submitted fields. | |
// Here we will use the same format the browser submits POST forms. | |
// You could use a different format, depending on your server, such | |
// as JSON or XML. | |
var formData = new FormData(); | |
for (var i = 0; i < formEl.length; ++i) { | |
formData.append(formEl[i].name, formEl[i].value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome