From 799e29af2417cb08261d033eef58672cf170f691 Mon Sep 17 00:00:00 2001 From: overplayed <47672088+overplayed@users.noreply.github.com> Date: Sat, 15 Mar 2025 23:08:56 -0400 Subject: [PATCH] Fixed form submission & conditional field visibility in main.js --- assets/js/main.js | 229 +++++++++++++++------------------------ auth-manager.php | 38 +++---- forms/questionnaire.html | 12 +- 3 files changed, 115 insertions(+), 164 deletions(-) diff --git a/assets/js/main.js b/assets/js/main.js index dca5c5e..6512db4 100644 --- a/assets/js/main.js +++ b/assets/js/main.js @@ -1,148 +1,97 @@ document.addEventListener("DOMContentLoaded", function () { - const form = document.getElementById("assessment-form"); - const submitButton = form.querySelector("button[type='submit']"); + // 🚀 Automatically load existing responses if available + fetch("load-responses.php") + .then(response => response.json()) + .then(data => prepopulateForm(data)) + .catch(error => console.error("Failed to load form responses:", error)); - // Function to toggle "Other" text fields when checkboxes are selected - function toggleOtherField(checkbox, textFieldId) { - const textField = document.getElementById(textFieldId); - textField.style.display = checkbox.checked ? "block" : "none"; - } + // 🚀 Handle Form Submission via AJAX + document.getElementById("assessment-form").addEventListener("submit", function (event) { + event.preventDefault(); // Prevent normal form submission - // Function to toggle dependent fields based on selection - function toggleDependentField(selectElement, valueToShow, dependentFieldId) { - const field = document.getElementById(dependentFieldId); - field.style.display = selectElement.value === valueToShow ? "block" : "none"; - } + const formData = new FormData(this); - // Track form changes to prevent unnecessary submissions - let formChanged = false; - - form.addEventListener("input", function () { - formChanged = true; - submitButton.disabled = false; - }); - - // Handle form submission via AJAX - form.addEventListener("submit", function (event) { - event.preventDefault(); - - if (!formChanged) { - showMessage("danger", "No changes detected. Please update the form before submitting."); - return; - } - - submitButton.disabled = true; - showMessage("info", "Submitting..."); - - const formData = new FormData(form); - - fetch("../submit.php", { - method: "POST", - body: formData - }) - .then(response => response.json()) - .then(data => { - if (data.success) { - showMessage("success", data.success); - formChanged = false; - submitButton.disabled = true; - } else { - showMessage("danger", data.error || "An error occurred."); - submitButton.disabled = false; - } - }) - .catch(() => { - showMessage("danger", "Network error. Please try again."); - submitButton.disabled = false; - }); - }); - - // Function to show messages on the form - function showMessage(type, text) { - let messageBox = document.getElementById("form-message"); - if (!messageBox) { - messageBox = document.createElement("div"); - messageBox.id = "form-message"; - messageBox.className = "alert mt-3 d-none"; - form.appendChild(messageBox); - } - messageBox.innerHTML = text; - messageBox.classList.remove("alert-success", "alert-danger", "alert-info", "d-none"); - messageBox.classList.add(type === "success" ? "alert-success" : "alert-danger"); - } - - - // Prepopulate the form if returning user - function prepopulateForm() { - fetch("../load-responses.php") - .then(response => response.json()) - .then(data => { - if (data.error) { - console.warn("Error loading responses:", data.error); - return; - } - - Object.keys(data).forEach(key => { - let field = document.querySelector(`[name="${key}"]`); - if (field) { - if (field.type === "checkbox") { - let values = JSON.parse(data[key] || "[]"); - values.forEach(value => { - let checkbox = document.querySelector(`[name="${key}"][value="${value}"]`); - if (checkbox) checkbox.checked = true; - }); - } else { - field.value = data[key]; - } - } - }); - - console.log("Form preloaded successfully."); - }) - .catch(error => console.error("Failed to load form responses:", error)); - } - - // Run prepopulation after DOM is loaded - document.addEventListener("DOMContentLoaded", prepopulateForm); - - - // Save form data to localStorage on change - form.addEventListener("input", function () { - let formData = {}; - new FormData(form).forEach((value, key) => { - formData[key] = value; - }); - localStorage.setItem("assessmentData", JSON.stringify(formData)); - }); - - fetch("../load-responses.php?token=" + new URLSearchParams(window.location.search).get("token")) - .then(response => response.json()) - .then(data => { - if (data.error) { - document.getElementById("auth-message").style.display = "block"; - } else { - document.getElementById("assessment-form").style.display = "block"; - if (data.is_board_member == 1) { - document.getElementById("board-member-section").style.display = "block"; - document.getElementById("board-member-image").src = data.board_member_image; + fetch("submit.php", { + method: "POST", + body: formData + }) + .then(response => response.json()) + .then(data => { + if (data.success) { + showMessage("success", data.success); + } else { + showMessage("danger", data.error || "Something went wrong."); } - // Fetch board member data -fetch("../board-member.php") -.then(response => response.json()) -.then(data => { - if (data.is_board_member) { - document.getElementById("board-member-questions").style.display = "block"; - } -}) -.catch(error => console.error("Failed to load board member data:", error)); - -prepopulateForm(); - - } - }) - .catch(error => { - console.error("Failed to validate token:", error); - document.getElementById("auth-message").style.display = "block"; + }) + .catch(error => { + console.error("Submission error:", error); + showMessage("danger", "Failed to submit the form."); + }); }); + // 🚀 Dynamic Fields - Show/Hide Textboxes Based on Selection + document.querySelectorAll("input[type=checkbox], input[type=radio], select").forEach(input => { + input.addEventListener("change", function () { + toggleDependentFields(); + }); + }); + + // Initial check on page load + toggleDependentFields(); }); + +// ✅ Prepopulate the form with existing responses +function prepopulateForm(data) { + if (data.error) { + console.error("Error loading responses:", data.error); + return; + } + + Object.keys(data).forEach(key => { + let input = document.querySelector(`[name="${key}"]`); + if (!input) return; + + if (input.type === "checkbox" || input.type === "radio") { + document.querySelectorAll(`[name="${key}"]`).forEach(option => { + option.checked = data[key].includes(option.value); + }); + } else { + input.value = data[key]; + } + }); + + toggleDependentFields(); // Ensure dependent fields are updated +} + +// ✅ Show message function (Bootstrap alert) +function showMessage(type, message) { + let messageDiv = document.getElementById("form-message"); + messageDiv.className = `alert alert-${type}`; + messageDiv.textContent = message; + messageDiv.classList.remove("d-none"); +} + +// ✅ Handle Conditional Fields (Show/Hide) +function toggleDependentFields() { + let toggleMappings = { + "mfa": ["mfa-types-section"], + "mfa_types[]": ["mfa-app-section"], + "personal_device": ["device-options-section"], + "board_doc_access": ["access_issues_details"], + "meeting_issues": ["meeting_issues_details"], + "it_challenges[]": ["it-challenges-other-text"], + "security_concerns[]": ["security-other-text"], + "file_storage[]": ["file-storage-other-text"], + "critical_files[]": ["critical-files-other-text"] + }; + + Object.keys(toggleMappings).forEach(trigger => { + let elements = document.querySelectorAll(`[name="${trigger}"]`); + let targetIds = toggleMappings[trigger]; + + let shouldShow = Array.from(elements).some(el => el.checked && el.value === "Other" || el.value === "Yes"); + targetIds.forEach(id => { + document.getElementById(id).style.display = shouldShow ? "block" : "none"; + }); + }); +} diff --git a/auth-manager.php b/auth-manager.php index 7bda2bf..9f7df56 100644 --- a/auth-manager.php +++ b/auth-manager.php @@ -1,54 +1,46 @@ connect_error) { - error_log("Database connection error: " . $conn->connect_error); die("Database connection error."); } -// Fetch user information, including token expiration -$query = "SELECT id, email, given_name, surname, is_board_member, token_expires_at FROM users WHERE auth_token = ?"; -$stmt = $conn->prepare($query); +// Fetch user information from database +$stmt = $conn->prepare("SELECT id, email, given_name, surname, is_board_member, expired FROM users WHERE auth_token = ?"); $stmt->bind_param("s", $authToken); $stmt->execute(); $result = $stmt->get_result(); - -if ($result->num_rows === 0) { - die("Unauthorized access - Invalid token."); -} - $user = $result->fetch_assoc(); -// Check if token is expired -if (strtotime($user['token_expires_at']) < time()) { - die("Unauthorized access - Token expired. Please contact your administrator."); +// Check if the token is valid and not expired +if (!$user || $user['expired'] == 1) { + die("Unauthorized access - Invalid or expired token."); } -// Store session data -$_SESSION['auth_token'] = $authToken; // Store token for future use +// Store user details in session $_SESSION['user_id'] = intval($user['id']); $_SESSION['email'] = $user['email']; $_SESSION['full_name'] = $user['given_name'] . " " . $user['surname']; -$_SESSION['is_board_member'] = intval($user['is_board_member']); +$_SESSION['is_board_member'] = intval($user['is_board_member']); -// Redirect only if using URL token -if (isset($_GET['auth']) && !isset($_SESSION['auth_token'])) { - header("Location: questionnaire.php"); +// Redirect users to questionnaire page if authentication was done via URL +if (isset($_GET['auth'])) { + header("Location: questionnaire.html"); exit; } ?> diff --git a/forms/questionnaire.html b/forms/questionnaire.html index bcfa9e7..fbf6192 100644 --- a/forms/questionnaire.html +++ b/forms/questionnaire.html @@ -19,8 +19,18 @@
Welcome,
+
+