document.addEventListener('DOMContentLoaded', function () { const btnCaricaAltro = document.getElementById('btn-carica-altro'); const contenitore = document.getElementById('itemsList'); const loadingMsg = document.getElementById('loading-msg'); btnCaricaAltro.addEventListener('click', function () { caricaAltro(); }); function caricaAltro() { // 1. Quanti elementi ci sono già in pagina const elementiAttuali = contenitore.querySelectorAll('.item').length; // 2. Quanti elementi caricare nella prossima chiamata const perPagina = parseInt(btnCaricaAltro.dataset.perPagina, 10) || 10; // Disabilito il bottone e mostro il loading, per evitare click multipli btnCaricaAltro.disabled = true; loadingMsg.style.display = 'block'; // 3. Chiamata AJAX (fetch) a load-more.php const params = new URLSearchParams({ offset: elementiAttuali, // da dove partire limit: perPagina, // quanti elementi caricare lang: 'it' }); fetch('https://www.fondazionefamigliapiacenza.org/assets/ajax/load-more/load-more.php?' + params.toString(), { method: 'GET', headers: { 'X-Requested-With': 'XMLHttpRequest' } }) .then(function (response) { if (!response.ok) { throw new Error('Errore nella risposta del server: ' + response.status); } return response.json(); }) .then(function (data) { // data.items = array di oggetti da renderizzare // data.hasMore = boolean, indica se ci sono altri elementi da caricare if (data.items && data.items.length > 0) { renderElementi(data.items); } // Se non ci sono più elementi, nascondo il bottone if (!data.hasMore) { btnCaricaAltro.style.display = 'none'; } }) .catch(function (err) { console.error('Errore nel caricamento:', err); alert('Si è verificato un errore nel caricamento degli elementi.'); }) .finally(function () { btnCaricaAltro.disabled = false; loadingMsg.style.display = 'none'; }); } function renderElementi(items) { let html = ``; items.forEach(function (item) { html += `
`; }); document.querySelector('#itemsList .list').insertAdjacentHTML('beforeend', html); } });