I'm struggling with a (probably fairly simple) HTML & JavaScript issue. And as I'm not much of a frontend guy, I hope there is someone around here who can help me out.
Task: A friend with a website, which has been built in Wordpress using the Thrive theme, asked me to write some JavaScript code that calls an API each time a specific button is pressed. Thrive allows to inject custom code in the footer so I created a function to call the API and set it as onclick on the <a> tag of the button.
Simplied code:
async function dummy() {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
var requestOptions = {
method: "POST",
headers: myHeaders,
body: JSON.stringify({}),
redirect: "follow",
};
return fetch("some.api.com", requestOptions);
}
document.getElementById("button1").onclick = async function () {
var res = await dummy();
return res.ok;
};
Problem: While this works without issues in Chrome, Safari and mobile browsers struggle with it. Safari most of the time yields the following exception: Unhandled Promise Rejection: TypeError: Load failed.
I played a bit the awaits and at some point I could make it work on occasion, but never consistently.
Please, could you tell me what I'm overseeing?
PS: I'm aware that this is by no means secure and definitely not production-ready. This is meant to be used solely for demonstration purposes, hence, the quick & dirty way.
function dummy() {
return new Promise((resolve, reject) => {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
method: "GET",
headers: myHeaders,
body: JSON.stringify({}),
};
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => {
resolve(data);
})
.catch((error) => {
reject(error);
});
})
}
const main = async()=>{
console.log(await dummy());
console.log("foo bar")
}
main();