Fixed form submission & conditional field visibility in main.js
This commit is contained in:
parent
8a5652b308
commit
799e29af24
|
|
@ -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";
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,54 +1,46 @@
|
|||
<?php
|
||||
require_once __DIR__ . "/db.php";
|
||||
require_once 'db.php'; // Ensure this contains the DB connection
|
||||
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
|
||||
// Ensure token is provided via GET or Session
|
||||
// Check if authentication token is provided via GET or session
|
||||
if (!isset($_GET['auth']) && !isset($_SESSION['auth_token'])) {
|
||||
echo "Unauthorized access. Please use the correct link with your authentication token.";
|
||||
exit;
|
||||
die("Unauthorized access. No authentication token provided.");
|
||||
}
|
||||
|
||||
// Use session token if available, otherwise use URL token
|
||||
$authToken = $_SESSION['auth_token'] ?? $_GET['auth'];
|
||||
$_SESSION['auth_token'] = $authToken;
|
||||
|
||||
// Ensure database connection is valid
|
||||
// Connect to the database
|
||||
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
|
||||
if ($conn->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;
|
||||
}
|
||||
?>
|
||||
|
|
|
|||
|
|
@ -19,8 +19,18 @@
|
|||
<img id="board-member-image" src="../assets/img/ccah-logo.png" alt="Board Member Image" style="max-height:100px; display:none;">
|
||||
</div>
|
||||
<h3 class="text-center">CCAH IT Assessment Questionnaire</h3>
|
||||
<p id="board-member-message" class="text-center fw-bold" style="display:none;">Welcome, Board Member!</p>
|
||||
<div class="alert alert-info text-center">
|
||||
<p>Welcome, <strong><?php echo $_SESSION['given_name'] ?? 'User'; ?></strong></p>
|
||||
</div>
|
||||
|
||||
<!-- Board Member Profile Image (Only shown if the user is a board member) -->
|
||||
<?php if (!empty($_SESSION['is_board_member']) && $_SESSION['is_board_member'] == 1): ?>
|
||||
<div class="text-center mb-3">
|
||||
<img src="img/board-member-placeholder.png" alt="Board Member" style="max-height: 120px; border-radius: 50%;">
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
|
||||
|
||||
<form id="assessment-form">
|
||||
<div id="form-message" class="alert d-none mt-3"></div>
|
||||
|
|
|
|||
Loading…
Reference in New Issue