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 () {
|
document.addEventListener("DOMContentLoaded", function () {
|
||||||
const form = document.getElementById("assessment-form");
|
// 🚀 Automatically load existing responses if available
|
||||||
const submitButton = form.querySelector("button[type='submit']");
|
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
|
// 🚀 Handle Form Submission via AJAX
|
||||||
function toggleOtherField(checkbox, textFieldId) {
|
document.getElementById("assessment-form").addEventListener("submit", function (event) {
|
||||||
const textField = document.getElementById(textFieldId);
|
event.preventDefault(); // Prevent normal form submission
|
||||||
textField.style.display = checkbox.checked ? "block" : "none";
|
|
||||||
}
|
|
||||||
|
|
||||||
// Function to toggle dependent fields based on selection
|
const formData = new FormData(this);
|
||||||
function toggleDependentField(selectElement, valueToShow, dependentFieldId) {
|
|
||||||
const field = document.getElementById(dependentFieldId);
|
|
||||||
field.style.display = selectElement.value === valueToShow ? "block" : "none";
|
|
||||||
}
|
|
||||||
|
|
||||||
// Track form changes to prevent unnecessary submissions
|
fetch("submit.php", {
|
||||||
let formChanged = false;
|
method: "POST",
|
||||||
|
body: formData
|
||||||
form.addEventListener("input", function () {
|
})
|
||||||
formChanged = true;
|
.then(response => response.json())
|
||||||
submitButton.disabled = false;
|
.then(data => {
|
||||||
});
|
if (data.success) {
|
||||||
|
showMessage("success", data.success);
|
||||||
// Handle form submission via AJAX
|
} else {
|
||||||
form.addEventListener("submit", function (event) {
|
showMessage("danger", data.error || "Something went wrong.");
|
||||||
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 board member data
|
})
|
||||||
fetch("../board-member.php")
|
.catch(error => {
|
||||||
.then(response => response.json())
|
console.error("Submission error:", error);
|
||||||
.then(data => {
|
showMessage("danger", "Failed to submit the form.");
|
||||||
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";
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 🚀 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
|
<?php
|
||||||
require_once __DIR__ . "/db.php";
|
require_once 'db.php'; // Ensure this contains the DB connection
|
||||||
|
|
||||||
if (session_status() === PHP_SESSION_NONE) {
|
if (session_status() === PHP_SESSION_NONE) {
|
||||||
session_start();
|
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'])) {
|
if (!isset($_GET['auth']) && !isset($_SESSION['auth_token'])) {
|
||||||
echo "Unauthorized access. Please use the correct link with your authentication token.";
|
die("Unauthorized access. No authentication token provided.");
|
||||||
exit;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use session token if available, otherwise use URL token
|
// Use session token if available, otherwise use URL token
|
||||||
$authToken = $_SESSION['auth_token'] ?? $_GET['auth'];
|
$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);
|
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
|
||||||
if ($conn->connect_error) {
|
if ($conn->connect_error) {
|
||||||
error_log("Database connection error: " . $conn->connect_error);
|
|
||||||
die("Database connection error.");
|
die("Database connection error.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch user information, including token expiration
|
// Fetch user information from database
|
||||||
$query = "SELECT id, email, given_name, surname, is_board_member, token_expires_at FROM users WHERE auth_token = ?";
|
$stmt = $conn->prepare("SELECT id, email, given_name, surname, is_board_member, expired FROM users WHERE auth_token = ?");
|
||||||
$stmt = $conn->prepare($query);
|
|
||||||
$stmt->bind_param("s", $authToken);
|
$stmt->bind_param("s", $authToken);
|
||||||
$stmt->execute();
|
$stmt->execute();
|
||||||
$result = $stmt->get_result();
|
$result = $stmt->get_result();
|
||||||
|
|
||||||
if ($result->num_rows === 0) {
|
|
||||||
die("Unauthorized access - Invalid token.");
|
|
||||||
}
|
|
||||||
|
|
||||||
$user = $result->fetch_assoc();
|
$user = $result->fetch_assoc();
|
||||||
|
|
||||||
// Check if token is expired
|
// Check if the token is valid and not expired
|
||||||
if (strtotime($user['token_expires_at']) < time()) {
|
if (!$user || $user['expired'] == 1) {
|
||||||
die("Unauthorized access - Token expired. Please contact your administrator.");
|
die("Unauthorized access - Invalid or expired token.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Store session data
|
// Store user details in session
|
||||||
$_SESSION['auth_token'] = $authToken; // Store token for future use
|
|
||||||
$_SESSION['user_id'] = intval($user['id']);
|
$_SESSION['user_id'] = intval($user['id']);
|
||||||
$_SESSION['email'] = $user['email'];
|
$_SESSION['email'] = $user['email'];
|
||||||
$_SESSION['full_name'] = $user['given_name'] . " " . $user['surname'];
|
$_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
|
// Redirect users to questionnaire page if authentication was done via URL
|
||||||
if (isset($_GET['auth']) && !isset($_SESSION['auth_token'])) {
|
if (isset($_GET['auth'])) {
|
||||||
header("Location: questionnaire.php");
|
header("Location: questionnaire.html");
|
||||||
exit;
|
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;">
|
<img id="board-member-image" src="../assets/img/ccah-logo.png" alt="Board Member Image" style="max-height:100px; display:none;">
|
||||||
</div>
|
</div>
|
||||||
<h3 class="text-center">CCAH IT Assessment Questionnaire</h3>
|
<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">
|
<form id="assessment-form">
|
||||||
<div id="form-message" class="alert d-none mt-3"></div>
|
<div id="form-message" class="alert d-none mt-3"></div>
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue