I am trying to load some data from a MySQL database into an HTML website. My approach at the moment is a PHP script that returns the database data as JSON and then a JS script that uses this data for creating the HTML elements.
All is being hosted on a webserver, and currently with all files in the same directory. When running I receive the following error:
GET http://www.<website>.com/fetch_data.php 404 (Not Found)
This is my PHP script:
<?php
// Create a connection to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check if the connection was successful
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Construct the SQL query to retrieve player data
$sql = "SELECT * FROM players";
// Execute the SQL query and store the result
$result = $conn->query($sql);
// Check if any rows were returned
if ($result->num_rows > 0) {
$players = array();
// Loop through each row and store the player data in an array
while ($row = $result->fetch_assoc()) {
$player = array(
"name" => $row["name"],
"description" => $row["description"],
"hcp" => $row["hcp"],
"image" => $row["image"]
);
array_push($players, $player);
}
// Encode the array as JSON and return it
header('Content-Type: application/json');
echo json_encode($players);
} else {
echo "No players found";
}
// Close the database connection
$conn->close();
?>
And this is my JS script that I include in my HTML:
// Container reference
const gridContainer = document.querySelector(".grid-container");
// Fetch the data from the database
const xhr = new XMLHttpRequest();
xhr.open("GET", "./fetch_data.php");
xhr.onload = function() {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
// Loop through the data and create a grid item for each player
data.forEach(player => {
const gridItem = document.createElement("div");
gridItem.classList.add("grid-item");
gridItem.innerHTML = `
<div class="top-wrapper">
<div class="img-wrapper">
<img src="pics/${player.image}" alt="${player.name}">
</div>
<div class="info-wrapper">
<h2>${player.name}</h2>
<p>${player.description}</p>
</div>
</div>
<div class="stats-wrapper">
<div class="stats-item">
<h3>HCP</h3>
<p>#${player.hcp}</p>
</div>
</div>
<div class="input-wrapper">
<input type="text" placeholder="???"/>
<button class="input-btn"><i class="fa-solid fa-paper-plane"></i></button>
</div>
`;
gridContainer.appendChild(gridItem);
});
} else {
console.error(xhr.statusText);
}
};
xhr.send();
Any help is appreciated – feel free to give input on my approach as well.