Home > Software engineering >  Using data-attributes and using them for a XML HTTP Request
Using data-attributes and using them for a XML HTTP Request

Time:11-13

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.

CodePudding user response:

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 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...
    });
}
  • Related