]> SAFE projects GIT repository - jmp/mailleur/commitdiff
Restarting selectajax.js
authorJean-Marc Pigeon <jmp@safe.c>
Wed, 17 Dec 2025 01:03:12 +0000 (20:03 -0500)
committerJean-Marc Pigeon <jmp@safe.c>
Wed, 17 Dec 2025 01:03:12 +0000 (20:03 -0500)
www/selectajax.js
www/selectajax.js.ang [new file with mode: 0644]
www/selectajax.js.fra [new file with mode: 0644]

index b89f0fcc52e04ac72f8599fd02d8293b5440ffea..8920fd54aa21d2433331fd98206410cd6ac5f429 100644 (file)
@@ -1,73 +1,67 @@
-/**
- * selectajax.js
- *
- * Gère l'envoi POST AJAX pour la sélection de colonnes et la recherche,
- * puis met à jour dynamiquement le tableau HTML dans lvlmai.php.
- *
- * Dépendances : aucun framework nécessaire (vanilla JS)
- */
 document.addEventListener('DOMContentLoaded', function() {
 
-    // Sélection du formulaire
     const form = document.getElementById('searchForm');
-    if (!form) return; // sécurité si formulaire non présent
+    if (!form) return;
 
     form.addEventListener('submit', function(e) {
-        e.preventDefault(); // empêche le rechargement de la page
+        e.preventDefault();
 
-        // Construction du FormData pour POST
         const formData = new FormData(form);
-
-        // Indiquer au backend qu'on veut du JSON
         formData.set('ajax', '1');
 
-        // Envoi POST via fetch
-        fetch('lvlmai.php', { method: 'POST', body: formData })
-            .then(resp => resp.text())
-            .then(text => {
-                console.log("Réponse brute :", text); // JMPDBG1
-                try {
-                    return JSON.parse(text);
-                } catch(err) {
-                    console.error("Erreur parsing JSON :", err, text);
-                    throw err;
-                }
-            })
-            .then(data => {
-                const headerRow = document.getElementById('headerRow');
-                const bodyRows = document.getElementById('bodyRows');
-                if (!headerRow || !bodyRows) {
-                    console.error("thead ou tbody introuvable !");
-                    return;
-                }
+        fetch('lvlmai.php', {
+            method: 'POST',
+            body: formData
+        })
+        .then(response => {
+            if (!response.ok) {
+                throw new Error("HTTP error " + response.status);
+            }
+            return response.json();   // 🔴 ÉTAPE MANQUANTE
+        })
+        .then(data => {
 
-                // Vider le tableau précédent
-                headerRow.innerHTML = '';
-                bodyRows.innerHTML = '';
+            console.log("JMPDBG data:", data);
 
-                console.log("JMPDBG2 nombre de lignes reçues :", data.rows.length);
+            if (!data.rows) {
+                console.error("No data.rows in response");
+                return;
+            }
 
-                if (data.rows.length === 0) return; // rien à afficher
+            const headerRow = document.getElementById('headerRow');
+            const bodyRows  = document.getElementById('bodyRows');
 
-                // Générer les en-têtes dynamiques
-                Object.keys(data.rows[0]).forEach(col => {
-                    const th = document.createElement('th');
-                    th.textContent = col;
-                    headerRow.appendChild(th);
-                });
+            if (!headerRow || !bodyRows) {
+                console.error("thead or tbody not found");
+                return;
+            }
+
+            headerRow.innerHTML = '';
+            bodyRows.innerHTML  = '';
+
+            console.log("JMPDBG rows:", data.rows.length);
+
+            if (data.rows.length === 0) return;
+
+            // Headers
+            Object.keys(data.rows[0]).forEach(col => {
+                const th = document.createElement('th');
+                th.textContent = col;
+                headerRow.appendChild(th);
+            });
 
-                // Générer les lignes
-                data.rows.forEach(row => {
-                    const tr = document.createElement('tr');
-                    Object.values(row).forEach(val => {
-                        const td = document.createElement('td');
-                        td.textContent = val ?? ''; // gérer les null
-                        tr.appendChild(td);
-                    });
-                    bodyRows.appendChild(tr);
+            // Rows
+            data.rows.forEach(row => {
+                const tr = document.createElement('tr');
+                Object.values(row).forEach(val => {
+                    const td = document.createElement('td');
+                    td.textContent = val ?? '';
+                    tr.appendChild(td);
                 });
-            })
-            .catch(err => console.error('Erreur AJAX:', err));
+                bodyRows.appendChild(tr);
+            });
+        })
+        .catch(err => console.error("AJAX error:", err));
     });
 });
 
diff --git a/www/selectajax.js.ang b/www/selectajax.js.ang
new file mode 100644 (file)
index 0000000..3791aed
--- /dev/null
@@ -0,0 +1,88 @@
+/**
+ * selectajax.js
+ *
+ * Handles AJAX POST for column selection and search input,
+ * then dynamically updates the HTML table in lvlmai.php.
+ *
+ * Dependencies: vanilla JS only
+ *
+ * Main contributor: Chap, iteration-ref: 20251216-001
+ *
+ * Usage: include this script at the end of the HTML body to ensure DOM readiness.
+ */
+
+function initSelectAjax(retryCount = 0) {
+    const maxRetries = 20;   // maximum retry attempts if DOM not ready
+
+    const form = document.getElementById('searchForm');
+    const headerRow = document.getElementById('headerRow');
+    const bodyRows = document.getElementById('bodyRows');
+
+    if (!form || !headerRow || !bodyRows) {
+        if (retryCount < maxRetries) {
+            console.log("initSelectAjax: DOM not ready, retry #" + (retryCount + 1));
+            setTimeout(() => initSelectAjax(retryCount + 1), 100); // wait 100ms
+        } else {
+            console.error("initSelectAjax: DOM elements not found after max retries");
+        }
+        return;
+    }
+
+    form.addEventListener('submit', function(e) {
+        e.preventDefault(); // prevent page reload
+
+        const formData = new FormData(form);
+        formData.set('ajax', '1');
+
+        fetch('lvlmai.php', {
+            method: 'POST',
+            body: formData
+        })
+        .then(resp => resp.text())
+        .then(text => {
+            console.log("Raw response:", text);
+            try {
+                return JSON.parse(text);
+            } catch(err) {
+                console.error("Failed to parse JSON:", err);
+                throw err;
+            }
+        })
+        .then(data => {
+            if (!data.rows) {
+                console.error("No 'rows' in response data");
+                return;
+            }
+
+            // Clear previous table content
+            headerRow.innerHTML = '';
+            bodyRows.innerHTML = '';
+
+            // Populate table header dynamically
+            const keys = Object.keys(data.rows[0]);
+            keys.forEach(col => {
+                const th = document.createElement('th');
+                th.textContent = col;
+                headerRow.appendChild(th);
+            });
+
+            // Populate table body
+            data.rows.forEach(row => {
+                const tr = document.createElement('tr');
+                keys.forEach(key => {
+                    const td = document.createElement('td');
+                    td.textContent = row[key];
+                    tr.appendChild(td);
+                });
+                bodyRows.appendChild(tr);
+            });
+
+            console.log("Table updated with", data.rows.length, "rows");
+        })
+        .catch(err => console.error("AJAX error:", err));
+    });
+}
+
+// Initialize after script load
+document.addEventListener('DOMContentLoaded', initSelectAjax);
+
diff --git a/www/selectajax.js.fra b/www/selectajax.js.fra
new file mode 100644 (file)
index 0000000..3489907
--- /dev/null
@@ -0,0 +1,64 @@
+function initSelectAjax(retryCount = 0) {
+    const maxRetries = 20;   // nombre maximum de tentatives
+    const form = document.getElementById('searchForm');
+    const headerRow = document.getElementById('headerRow');
+    const bodyRows = document.getElementById('bodyRows');
+
+    if (!form || !headerRow || !bodyRows) {
+        if (retryCount < maxRetries) {
+            console.warn(`DOM incomplet, réessai ${retryCount + 1}/${maxRetries} dans 100ms...`);
+            setTimeout(() => initSelectAjax(retryCount + 1), 100);
+        } else {
+            console.error("Échec d'initialisation AJAX : DOM incomplet après 20 tentatives");
+        }
+        return;
+    }
+
+    form.addEventListener('submit', function(e) {
+        e.preventDefault();
+
+        const formData = new FormData(form);
+        formData.set('ajax', '1');
+
+        fetch('lvlmai.php', { method: 'POST', body: formData })
+            .then(resp => resp.text())
+            .then(text => {
+                console.log("Réponse brute :", text);
+                try {
+                    return JSON.parse(text);
+                } catch(err) {
+                    console.error("Erreur parsing JSON :", err, text);
+                    throw err;
+                }
+            })
+            .then(data => {
+                headerRow.innerHTML = '';
+                bodyRows.innerHTML = '';
+
+                if (!data.rows || data.rows.length === 0) return;
+
+                // en-têtes
+                Object.keys(data.rows[0]).forEach(col => {
+                    const th = document.createElement('th');
+                    th.textContent = col;
+                    headerRow.appendChild(th);
+                });
+
+                // lignes
+                data.rows.forEach(row => {
+                    const tr = document.createElement('tr');
+                    Object.values(row).forEach(val => {
+                        const td = document.createElement('td');
+                        td.textContent = val ?? '';
+                        tr.appendChild(td);
+                    });
+                    bodyRows.appendChild(tr);
+                });
+            })
+            .catch(err => console.error('Erreur AJAX:', err));
+    });
+}
+
+// Appel sécurisé au chargement du DOM
+document.addEventListener('DOMContentLoaded', () => initSelectAjax());
+