Skip to content

Instantly share code, notes, and snippets.

@jbmoelker
Created January 9, 2016 18:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbmoelker/4b763e8e0d97021642f3 to your computer and use it in GitHub Desktop.
Save jbmoelker/4b763e8e0d97021642f3 to your computer and use it in GitHub Desktop.
Submit an HTMLFormElement asynchronously and receive a Promise which resolves with the response data.
export default function asyncSubmitForm (form:HTMLFormElement): Promise<Response> {
return window.fetch(formRequest(form))
.then(checkStatus)
.then(response => response.json());
}
export function formRequest(form:HTMLFormElement): Request {
return new Request(form.action, {
method: form.method,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/json'
},
body: new FormData(form)
});
}
// https://github.com/github/fetch#handling-http-error-statuses
function checkStatus(response:Response): Response {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw new Error(response.statusText);
// append original response to error?
}
}
<form id="demo" method="post" action="path/to/login">
<label>
username
<input name="username">
</label>
<label>
password
<input name="password" type="password">
</label>
<input type="submit" value="Log in">
</form>
import asyncSubmitForm from './async-submit-form';
const form = document.getElementById('demo');
form.addEventListener('submit', (event) => {
// do something to indicate form is processing
event.preventDefault();
asyncFormSubmit(form)
.then(data => {
// use response data (json) to update view
})
.catch(err => {
// handle error (eg. restore form and ...)
console.error(err);
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment