Single Import - AJAX / Javascript

Asked

Viewed 27 times

-1

Hello,

On my page, when loading a JSON it should be integrated into the file. This works. What I wanted is for him to do this import only once, if not he loads the same array as many times as I request. I tried to create a boolean variable so that when I first clicked JSON, but then no more. You can help me?

var botaoAdicionar = document.querySelector("#btn-buscar");

botaoAdicionar.addEventListener("click", function() {
  var xhr = new XMLHttpRequest();

  xhr.open("GET", "https://api-pacientes.herokuapp.com/pacientes");

  xhr.addEventListener("load", function() {
    var erroAjax = document.querySelector("#erro-ajax");
    if( xhr.status == 200) {
      erroAjax.classList.add("invisivel");
      var resposta = xhr.responseText;
      var pacientes = JSON.parse(resposta);

      pacientes.forEach(function(paciente) {
        adicionaPacienteNaTabela(paciente);
      });

    }else {
      erroAjax.classList.remove("invisivel");
    }

  });

  xhr.send();

});
  • Hi Patrick I don’t see any ajax in your code... you’ll have forgotten something?

  • Hi Sergio... I had copied the wrong file. Fixed.

  • Okay, so what about every click that should happen? that .forEach should still run if ajax is not needed because pacientes already exists? or all this code should run only once?

  • What happens: every time I click the button, the array in the api is loaded on my page (a list of clients). What should happen: click once, load this array and if I click again, it should not (because it has already been loaded beforehand)

1 answer

1

What is done for such cases is to remove the headphone from the event and disable the button after pressing once... this could be so:

const botaoAdicionar = document.querySelector("#btn-buscar");
const carregarPacientes = function() {
  const xhr = new XMLHttpRequest();

  const.open("GET", "https://api-pacientes.herokuapp.com/pacientes");

  xhr.addEventListener("load", function() {
    const erroAjax = document.querySelector("#erro-ajax");
    if (xhr.status == 200) {
      erroAjax.classList.add("invisivel");
      const pacientes = JSON.parse(xhr.responseText);
      pacientes.forEach(adicionaPacienteNaTabela);
      botaoAdicionar.removeEventListener("click", carregarPacientes);
      botaoAdicionar.disabled = true;
    } else {
      erroAjax.classList.remove("invisivel");
    }
  });
  xhr.send();
};

botaoAdicionar.addEventListener("click", carregarPacientes);

  • 1

    I will delete my answer, we included almost at the same time and it’s the same! I mean your best hand that was in one :)

  • 1

    @Leandrade is... came out of the oven at the same time :)

  • Personal thank you!!

Browser other questions tagged

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