Created
September 9, 2025 15:00
-
-
Save mscalora/896d86652b046f8df617c41338c5fc89 to your computer and use it in GitHub Desktop.
Client-side js helper function for POSTing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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