Level 73
I use two methods for ajax calls, one post and one get
async function getRequest(url, parameters = {}, loading = true) {
try {
if (loading) {
showLoading();
}
let responsePromise = await fetch(url, { method: 'GET', headers: parameters});
if(! responsePromise.ok) {
if(loading) {
hideLoading();
}
throw new Error(responsePromise.status );
}
if (loading) {
hideLoading();
}
return await responsePromise.json();
} catch (error) {
return error;
}
}
async function postRequest(url, parameters = {}, loading = true) {
try {
if (loading) {
showLoading();
}
let responsePromise = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams(parameters)
});
if(! responsePromise.ok) {
if (loading) {
hideLoading();
}
throw new Error(responsePromise.status );
}
if (loading) {
hideLoading();
}
return await responsePromise.json();
} catch (error) {
return error;
}
}