Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

216
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda