Skip to content

Instantly share code, notes, and snippets.

@seamusleahy
Last active May 4, 2019 19:17
Show Gist options
  • Save seamusleahy/e63911a939f73ec8588bd472ed07980d to your computer and use it in GitHub Desktop.
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.
// 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);
});
// 2. Make the request
// ================================
var url = '/echo/json/';
var fetchOptions = {
method: 'POST',
headers,
body: formData
};
var responsePromise = fetch(url, fetchOptions);
// 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);
}
@MWPAWAR
Copy link

MWPAWAR commented Nov 22, 2017

Awesome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment