Skip to content

Instantly share code, notes, and snippets.

@rubinhozzz
Last active February 20, 2019 08:49
Show Gist options
  • Save rubinhozzz/442f2163237428ce4fd02a8ce93ebf02 to your computer and use it in GitHub Desktop.
Save rubinhozzz/442f2163237428ce4fd02a8ce93ebf02 to your computer and use it in GitHub Desktop.
Sends a request through fetch using async / await.
/**
* Sends a request through fetch using async / await.
* @param {Object} request
*/
async function makeRequestCall(request) {
const response = await fetch(request);
const json = await response.json();
if (!response.ok) {
let error = new Error(response.statusText);
error.response = response;
error.errors = json;
throw error;
}
return json;
}
let data = serializeForm(document.getElementById('form_text'));
let request = new Request(urls.addSpecificationDetail, {
method: 'POST',
credentials: 'include',
headers: new Headers({
'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRFToken': getCookie('csrftoken'),
}),
body: data,
});
makeRequestCall(request)
.then(jsonResponse => console.log(jsonResponse))
.catch(error => {
console.log(error.errors);
writeErrorsFromAjaxForm('form_text', error.errors, 'id_text');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment