FIX: you dont have to require the API… the JS does its work whenever the DOM is loaded… thanks deceze:
<?php require 'includes/api/load_images.php';?>
I have a simple API that calls images from my database via JSON. Everything works fine, but there is text containing the JSON (which i dont want).
The problem is the text at the top
Here is my html where i call all the necesearry files:
<script src="/../public/js/gallery.js" defer></script>
<script src="/../public/js/lightbox.js" defer></script>
<?php require 'includes/api/load_images.php';?>
<div class="gallery-grid">
<div id="gallery">
<!-- Betöltött képek jelennek meg itt -->
</div>
</div>
<button id="loadMore" class="gallery-loadMore">Továbbiak betöltése</button>
<?php require 'includes/website_essentials/lightbox.php';?>
Here is my php API:
<?php
require_once __DIR__ . '/../../database/db_connect.php'; // Adatbázis kapcsolat
require_once __DIR__ . '/../../includes/errorhandler.php'; // Hibakezelő
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 6;
$offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;
$sql = "SELECT * FROM gallery ORDER BY uploaded_at DESC LIMIT $limit OFFSET $offset";
$result = $conn->query($sql);
$images = [];
while ($row = $result->fetch_assoc()) {
$images[] = $row;
}
echo json_encode($images);
$conn->close();
?>
And here is my JS:
document.addEventListener("DOMContentLoaded", function () {
let offset = 0;
const limit = 6;
function loadImages() {
fetch(`/includes/api/load_images.php?limit=${limit}&offset=${offset}`)
.then(response => response.json())
.then(images => {
console.log(images);
if (images.length === 0) {
document.getElementById("loadMore").style.display = "none";
return;
}
images.forEach((image, index) => {
const galleryItem = document.createElement("div");
galleryItem.classList.add("gallery-item");
const imgElement = document.createElement("img");
imgElement.setAttribute("loading", "lazy");
imgElement.setAttribute("data-index", index);
imgElement.classList.add("gallery-img");
imgElement.src = `/${image.gallery_image}`;
imgElement.alt = image.title;
imgElement.title = image.title;
galleryItem.appendChild(imgElement);
document.getElementById("gallery").appendChild(galleryItem);
});
// Képek betöltése után esemény kiváltása (ez a lightbox.js fájlban van kezelve)
document.dispatchEvent(new Event("imagesLoaded"));
offset += limit;
})
.catch(error => console.error("Hiba:", error));
}
loadImages();
document.getElementById("loadMore").addEventListener("click", loadImages);
});