Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
Fetching API when onClick event is triggered

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.

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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();

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!