Problem with fetch function using onClick event

Asked

Viewed 182 times

0

I am developing a logic that until then works perfectly. Access an API by fetch, receive a token and run an SQL call to another API, using the token received, then treat the return to be displayed within a logic of "rows x columns", simulating an approximate behavior of the INDICE+CORRESP functions, in Excel.

The problem is that the whole process runs on the loading of the HTML, because it is the standard behavior of Javascript.

By the logic, I should put this inside a function and call in the desired event, so I added a Switch to the button:

btn.addEventListener("click", event => {
  getReady();
});

And I tried to encapsulate all the code in one function, adding:

function getReady() {

at the beginning of the code and its closure at the end. However, I get an error message, in the browser:

TypeError: Failed to fetch

If I don’t use it as a function, everything runs perfectly but I don’t have control over the event I want to call the routine. Follow the entire code:

function getReady() {
  const main = document.getElementById("main");
  const user = document.getElementById("user");
  const pass = document.getElementById("pass");
  var setores = [];
  var servicos = [];
  var flagstatus = [];

  console.log(pass);

  fetch("https://api.gescorpgo.com/api/v8/usuarios/login.json", {
    method: "post",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      email: "**********",
      senha: "**********",
      modulo: "2"
    })
  })
    .then(function(response) {
      response.text().then(function(result) {
        const obj = JSON.parse(result);
        const tokenid = obj.user.token;

        main.innerHTML = `<div class="row mt-2 mb-2 justify-content-center">
        <div class="alert alert-success justify-content-center" role="alert">
            ${tokenid}</span>
        </div>`;

        fetch(
          `https://api.gescorpgo.com/api/query-browser.json?token=${tokenid}`,
          {
            method: "post", // opcional
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json"
            },
            body: JSON.stringify({
              stm:
                "SELECT DISTINCT rs.seq_relatorio, sp.seq, rs.label_rel_predinho, vw.id_subservico, vw.id_setor, right(ss.sub_servico,length(ss.sub_servico)-9) servico, sp.nome_setor pavimento, sp.nome_setor_abrev, vw.flag_status, sp.cor_rel_predinho FROM (SELECT @id_contrato := 6, @dt_ref_fim := '2020/03/23', @id_fechamento := 1) parm, vw_nortis_base_fluxo_servicos vw INNER JOIN tbl_relatorio_setup rs ON vw.id_subservico = rs.id_subservico AND rs.id_relatorio = 3 And rs.label_rel_predinho = 'TORRE' INNER JOIN tbl_subservico ss ON vw.id_subservico = ss.id_subservico INNER JOIN tbl_setores sp ON vw.id_setor = sp.id_setor ORDER BY rs.label_rel_predinho, rs.seq_relatorio asc, sp.seq desc;"
            })
          }
        )
          .then(function(response) {
            main.innerHTML = "";
            response.text().then(function(result) {
              const obj = JSON.parse(result);
              const query = obj.response;

              main.innerHTML = `<div class="card card-body mt-2"><div class="table-responsive">
                <table id="tbl" class="table-bordered table-responsive-sm" width="100%">`;

              //console.log(query);
              const tbl = document.getElementById("tbl");

              Object.keys(query).forEach(function(chave) {
                var prop = query[chave];
                if (typeof prop !== "object") mostrarConteudo(prop, chave);
                else setores = setores.concat(prop.nome_setor_abrev);
                servicos = servicos.concat(prop.servico);
                flagstatus = flagstatus.concat(prop.flag_status);
              });

              var innerHTML = "";
              var cor = "Snow";
              var i = 0;

              array_unique(setores).forEach(function(item, indice, array) {
                if (indice === 0) cor = "DarkSlateBlue";
                else if (indice === 1) cor = "DarkSlateBlue";
                else if (indice === 31) cor = "SaddleBrown";
                else if (indice === 32) cor = "SaddleBrown";
                else cor = "DarkGray";

                innerHTML =
                  innerHTML +
                  `<tr id= "${item}"><td class="setores" bgcolor="${cor}">${item}</td></tr>`;
              });

              innerHTML = innerHTML + `<tr class="foo smphone">`;
              innerHTML = innerHTML + `<td><div class="foo" ></div></td>`;

              array_unique(servicos).forEach(function(item, indice, array) {
                innerHTML =
                  innerHTML + `<td><div class="foo">${item}</div></td>`;
              });

              innerHTML = innerHTML + `</tr></table></div></div>`;
              tbl.innerHTML = innerHTML;

              for (i = 0; i < query.length; i++) {
                var trid = document.getElementById(query[i].nome_setor_abrev);
                `<td bgcolor="${cor}" class="data">&nbsp;&nbsp;&nbsp;</td>`;
                if ((query[i].nome_setor_abrev = trid)) {
                  if (query[i].flag_status === "1") cor = "Gold";
                  if (query[i].flag_status === "2") cor = "Gray";
                  if (query[i].flag_status === "3") cor = "DarkGreen";
                  if (query[i].flag_status === "4") cor = "LightGrey";
                  trid.innerHTML =
                    trid.innerHTML +
                    `<td bgcolor="${cor}" class="data">&nbsp;&nbsp;&nbsp;</td>`;
                  //console.log(trid.innerHTML);
                } else {
                }
              }
            });
          })
          .catch(function(err) {
            console.error(err);
          });
      });
    })
    .catch(function(err) {
      console.error(err);
    });
}

function array_unique(array) {
  return array.filter(function(el, index, arr) {
    return index == arr.indexOf(el);
  });
}

const btn = document.getElementById("btn");
btn.addEventListener("click", event => {
  getReady();
});
  • In short: I need to put this routine in a function and call it in the onClick of the Submit input

1 answer

0


Asynchronous declaration required async and await in the methods then, apparently the fecth is returning a Promise.

Example:

function getReady() {
  const resultElement = document.getElementById("result");

  fetch("https://api.gescorpgo.com/api/v8/usuarios/login.json", {
    method: "post",
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json"
    }
  })
    .then( async (response) => {
      resultElement.innerText = await response.text();
    })
    .catch(function (err) {
      console.log(err)
    });
}

const btn = document.getElementById("btn");
btn.addEventListener("click", (event) => {
  getReady();
});
<button id="btn">botão</button>
<div id="result"></div>

  • The test worked, but I’m not sure of this solution.

  • Kleber, thank you so much for your willingness to help me!

  • @Paulomonteiro, I took your code with your credentials and made it work with onClick follow the codepen https://codepen.io/kleberoliveira/pen/JjYPjep

  • 1

    Dear Kleber, Codepen ran, but not in my environment, so I investigated and found that there was some problem with HTML syntax that only appeared when using code as a function. I refactored the HTML directly into codepen and voila! All running. I really appreciate the help and I will take advantage of the answer to study the logic involved. Thank you very much!

  • if you can close the question.

  • I appreciate you instructing me, I haven’t figured out how yet.

  • chat and see this https://chat.stackexchange.com/rooms/106450/problema-com-a-funcao-fetch-usando-o-evento-onclick

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.