Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!