Level 73
I use the fetch api to do all my ajax calls.
async function postRequest(url, parameters = {}) {
try {
let responsePromise = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams(parameters)
});
if(! responsePromise.ok) {
throw new Error(responsePromise.status );
}
return await responsePromise.json();
} catch (error) {
return error;
}
}
You call it like
async function myAjaxCall() {
let params = {
somevalue: 1,
someothervalue: 2
};
let response = await postRequest('https://api.yoursite.com/someendpoint', params);
}
```
2 likes