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

124
Visualizações
Using data-attributes and using them for a XML HTTP Request

I have this button with a data attribute called "data-id" and its value is "1". The 1 is the id number for a car in my database.

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

When it's clicked I want to pass this id to my JavaScript where it will send this id to my PhP using XMLHttpRequest. This is what I have for the JavaScript

 <script>
        const buttons = document.querySelectorAll("[data-id]");
        buttons.forEach(button => {
            button.addEventListener("click", (loadCarDetails));
        });
        document.getElementById('car-details').addEventListener('click', loadCarDetails);

        function loadCarDetails() {
            let xhr = new XMLHttpRequest();


            xhr.open('GET', 'getCarDetails.php', true);
            xhr.onload = function () {
                if (this.status == 200) {
                    let carDetails = JSON.parse(this.responseText);
                    console.log(cars);

                   
                    //document.getElementById('users').innerHTML = output;
                }
            }
            xhr.send();
        }
    </script>

I need to somehow get the id and pass it to the getCarDetails.php which will return the details of the car using jSON. I need to use the id to perform a query in the getCarDetails.php. This is my PHP.

$connection = new mysqli("sever", "username", "password", "database");
$car_id = $_POST['car_id];
    if ($connection->connect_error){
        exit("Error connecting to the database");
    }
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $connection->set_charset("utf8mb4");
  
    $car_id = $connection->escape_string($_POST['car_id']);

   

    $stmt = $connection->prepare("SELECT car_drivetrain_lookup.drivetrain_type, car_suitability_lookup.car_suitability_type
    FROM cars
    INNER JOIN car_suitability_lookup ON car_suitability_lookup.lookup_id = cars.car_suitability_id
    INNER JOIN car_drivetrain_lookup ON car_drivetrain_lookup.lookup_id = cars.car_drivetrain_id
    WHERE cars.car_id = ?");
    $stmt->bind_param("i", $car_id);
    $stmt->execute();
    $result = $stmt->get_result();
    echo json_encode($result->fetch_all());

Can someone help me achieve this? I'm really new to JavaScript and would like to be pointed in the right direction.

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

0

There are two aspects to this:

  1. Getting the id from the clicked element, and
  2. Sending the correct kind of request to the server

The first part is simple. Your loadCarDetails function is called with an event object as the first argument, which has a currentTarget property referring to the element you hooked the function to, so we can get the data-* attribute from that:

function loadCarDetails(event) {
    const id = event.currentTarget.getAttribute("data-id");
    // ...
}

Then we need to do a POST (your current code does a GET instead) with that id as car_id. I wouldn't use XMLHttpRequest in new code, it's outdated; I'd use fetch:

function loadCarDetails(event) {
    const id = event.currentTarget.getAttribute("data-id");
    const body = new FormData();
    body.append("car_id", id);
    fetch("getCarDetails.php", {
        method: "POST",
        body
    })
    .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...
    });
}
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