Try this approach:
Calling a function in your code.
document.addEventListener("click", async function(e) {
if (e.target) {
if (Boolean(e.target.closest('span')?.classList.contains('addProduct'))) {
e.preventDefault();
if ('disabled' in e.target) e.target.disabled = true;
productId = parseInt(e.target.closest('tr')?.getAttribute('id').replace('product-', '')) || 0;
let form = new FormData();
form.append('productId', productId);
let result = await callApi('url-here', form);
console.log(result);
if ('disabled' in e.target) e.target.disabled = false;
}
}
});
Wrapper function (needed for processing Promise)
async function callApi(url, form, method = 'POST', type = 'json') { // text, json, blob, formData, arrayBuffer
try {
return await callApiSafe(url, form, method, type);
} catch (error) {
console.error('Error in callApiSafe:', error);
return null;
}
}
Data acquisition function
async function callApiSafe(url, form, method, type) {
try {
const response = await fetch(url, {
method: method,
cache: "no-store",
headers: { "X-Requested-With": "XMLHttpRequest" },
body: form
});
if (!response.ok) {
if (response.status === 404) throw new Error('404, Not found');
if (response.status === 500) throw new Error('500, Internal server error');
throw new Error(`HTTP error: ${response.status}`);
}
switch (type) {
case 'text':
return await response.text();
case 'json':
return await response.json();
case 'blob':
return await response.blob();
case 'formData':
return await response.formData();
case 'arrayBuffer':
return await response.arrayBuffer();
default:
throw new Error('Unsupported response type');
}
} catch (error) {
console.error('Request failed:', error);
throw error;
}
}