Skip to content

Instantly share code, notes, and snippets.

@mscalora
Created September 9, 2025 15:00
Show Gist options
  • Select an option

  • Save mscalora/896d86652b046f8df617c41338c5fc89 to your computer and use it in GitHub Desktop.

Select an option

Save mscalora/896d86652b046f8df617c41338c5fc89 to your computer and use it in GitHub Desktop.
Client-side js helper function for POSTing
function post(url, data, successCallback, errorCallback, responseType) {
fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams(data),
})
.then(response => {
if (!response.ok) { throw new Error(response.status); }
const contentType = response.headers.get('content-type');
const isJson = responseType === 'json' || (responseType === 'auto' && contentType && contentType.includes('application/json'))
return isJson ? response.json() : response.text();
})
.then(result => { successCallback(result);})
.catch(error => { errorCallback(parseInt(error.message, 10) || 0)})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment