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

308
Visualizações
When pressing button to trigger event nothing happens

I have a button that has a data-id with a value of 1. I need to pass this id to getCarDetails.php during a fetch() call. The getCarDetails needs this id for a query. The php is working fine as I tested it on a normal submit form and returns the jSON I need. However, this script doesn't want to work. I've tried everything.

function loadCarDetails(event) {
  const id = event.currentTarget.getAttribute("data-id");
  const data = new FormData();
  data.append("car_id", id);
  fetch("getCarDetails.php", {
      method: "POST",
      data
    })
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
      }
      return response.json();
    })
    .then(carDetails => {
      // ...use the car details here...
    })
    .catch(error => {
      // ...handle/reject error here...
    });
}
<div class="car-item">
  <div class="row">
    <p>Ford Fiesta</p>
  </div>

  <div class="row">
    <button type="button" class="btn" data-id="1">View</button>
  </div>
</div>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Since your buttons are dynamically generated, they need an additional class that you can identify:

<button type="button" class="btn btnview" data-id="1">View</button>

Then, add an event listener for them at the end of the javascript:

document.querySelectorAll('.btnview')
    .forEach((e, i) => e.addEventListener('click', loadCarDetails));

This means that when the user clicks one of the buttons, it would call the loadCarDetails function for that button.

about 4 years ago · Juan Pablo Isaza Relatório

0

You're not passing that function in a callback on the event handler of the button

               <div class="row">
                    <button type="button" onClick={(e) => loadCarDetails(e)} class="btn" data-id="1">View</button>
                </div>
about 4 years ago · Juan Pablo Isaza 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