Hi here is my js code i am doing 2 things, reading file users.json in login page and also creating a logfile with ext .elog for next page. all is done by pressing submit button, that proceed to next page name initialize.html and also create .elog file...
my problem is,
1. how i do auto save the logbox msgs in this .elog file after 10 seconds,i used setInterval() method but didnot work.
2. i saved the log msgs by pressing a button named proceed on initliaze.hmtl that moves the elog file to next page, but at the same time the logbox msgs disappear, i want to keep these msgs on screen in logBox...
3. the .elog file shifted to next page by pressing procced button , i want to append this file, that page also has a logbox. the actions performed in that page should be append in that .elog file.
Any help will be appreciated. thanks..
sharing my code for correction and implementing the required things...
here is my js code..Detail is written in comments
login.js
//Toggle Eye Icon
function togglePasswordVisibility() {
var passwordInput = document.getElementById("password");
var eyeIcon = document.querySelector(".icon1");
if (passwordInput.type === "password") {
passwordInput.type = "text";
eyeIcon.src = "img/eye-show.png"; // Change the source to the eye-off icon
} else {
passwordInput.type = "password";
eyeIcon.src =`
your text`
"img/eye-hide.png";// Change the source back to the eye icon
}
}
//User Authentication
async function authenticateUserAndCreateLogFile() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
fetch('users.json')
.then(response => response.json())
.then(users => {
var authenticatedUser = users.find(function (user) {
return user.username === username && user.password === password;
});
if (authenticatedUser) {
localStorage.setItem('username', username);
// Create and download the log file upon successful login
createAndDownloadLogFile(username);
// Redirect to the welcome page after successful login
window.location.href = 'initialize.html';
} else {
// alert('Invalid username or password. Please try again.');
}
})
.catch(error => console.error('Error fetching users:', error));
}
// Rest of your code remains unchanged
// ...
//Loading Username file
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'users.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4) {
if (xobj.status == 200) {
callback(null, JSON.parse(xobj.responseText));
} else {
callback("Error loading JSON file", null);
}
}
};
xobj.send(null);
}
function checkCredentials(username, password, users) {
if (!users || !Array.isArray(users)) {
console.error("Invalid user data");
return false;
}
for (var i = 0; i < users.length; i++) {
if (users[i].username === username && users[i].password === password) {
return true; // Credentials matched
}
}
return false; // Credentials not found
}
var loginMessage;
// Call loadJSON
loadJSON(function(error, data) {
if (error) {
console.error("Error loading JSON file:", error);
} else {
console.log("JSON file loaded successfully:", data);
// Handle form submission and login logic
var loginForm = document.getElementById("loginForm");
loginForm.addEventListener("submit", function (event) {
event.preventDefault(); // Prevent the default form submission
var usernameInput = document.getElementById("username");
var passwordInput = document.getElementById("password");
var username = usernameInput.value;
var password = passwordInput.value;
// Check credentials
var isAuthenticated = false;
var isRegistered = false;
for (var i = 0; i < data.length; i++) {
if (data[i].username === username) {
isRegistered = true;
if (data[i].password === password) {
isAuthenticated = true;
break;
}
}
}
var isAuthenticated = checkCredentials(username, password, data);
if (isAuthenticated) {
alert("Login successful!");
var loginMessage = "User '" + username + "' logged in successfully.";
localStorage.setItem("loginMessage", loginMessage); // Store message in localStorage
window.location.href = "initialize.html";
// Redirect to a different page or perform any other action
} else if (!isRegistered) {
openModal("User is not registered. Kindly contact the administrator.");
event.preventDefault();
} else {
// Incorrect password, display error message below password input
var errorMessage = document.createElement("div");
console.log("Wrong Password");
errorMessage.style.color = "red";
errorMessage.innerText = "Incorrect credentials. Please try again.";
errorMessage.style.display = "block";
errorMessage.style.marginTop = "5px"; // Adjust the gap here
errorMessage.style.fontSize = "16px"; // Set the font size here
errorMessage.style.fontWeight = "bold"; // Set the font size here
passwordInput.parentNode.appendChild(errorMessage);
}
});
}
});
function createAndDownloadLogFile(username) {
var currentDate = new Date();
var formattedDate = currentDate.toISOString().split('T')[0];
var formattedTime = currentDate.toTimeString().split(' ')[0].replace(/:/g, '-');
var logMessage = formattedDate + ' ' + formattedTime + ': ' + username + ' logged in.\n';
var filename = formattedDate + '-' + formattedTime + '-' + username + '.elog';
// Save the log message to sessionStorage
// var existingLogs = sessionStorage.getItem('logMessages') || '';
// sessionStorage.setItem('logMessages', existingLogs + logMessage);
// logToBox(logMessage);
// var logContent = ''; // Add content to log if needed
var blob = new Blob([logContent], { type: 'text/plain' });
var a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
function saveLoginToLogFile(username) {
var currentDate = new Date();
var formattedDate = currentDate.toISOString().split('T')[0];
var formattedTime = currentDate.toTimeString().split(' ')[0].replace(/:/g, '-');
var logMessage = formattedDate + ' ' + formattedTime + ': ' + username + ' logged in.\n';
// Create a data URI for the log message
var dataURI = 'data:text/plain;charset=utf-8,' + encodeURIComponent(logMessage);
// Create a temporary anchor element
var a = document.createElement('a');
a.href = dataURI;
a.download = '';
// Append the anchor to the body and click it to trigger download
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
// Functions for custom modal
function openModal(message) {
const modal = document.getElementById("errorModal");
const modalText = document.getElementById("modalText");
if (modal && modalText) {
modalText.innerText = message;
modal.style.display = "block";
} else {
console.error("Modal elements not found.");
}
}
function closeModal() {
const modal = document.getElementById("errorModal");
if (modal) {
modal.style.display = "none";
} else {
console.error("Modal element not found.");
}
// Prevent form submission
return false;
}
function openDialog() {
// Display the confirmation dialog
const dialogOverlay = document.getElementById('dialogOverlay');
if (dialogOverlay) {
dialogOverlay.style.display = 'block';
} else {
console.error("Dialog overlay element not found.");
}
}
function closeDialog() {
// Hide the confirmation dialog
const dialogOverlay = document.getElementById('dialogOverlay');
if (dialogOverlay) {
dialogOverlay.style.display = 'none';
} else {
console.error("Dialog overlay element not found.");
}
}
function handleNo(event) {
// Handle "No" button click
closeDialog();
event.stopPropagation();
event.preventDefault(); // Prevent the default button behavior
}
function handleYes(event) {
// Handle "Yes" button click
alert("Cancelled!");
closeDialog();
event.preventDefault(); // Prevent the default button behavior
}
function logout() {
localStorage.removeItem('username');
localStorage.removeItem('userRole');
window.location.href = 'initialize.html';
}
2. initial_script.js...
////////////////////////////////////////////////////////
//Check if User Exist
var loginMessage = localStorage.getItem("loginMessage");
console.log("retrieved");
// Check if login message exists
if (loginMessage) {
var log = document.getElementById("log");
var messageDiv = document.createElement("div");
messageDiv.textContent = "" + loginMessage; // Add a line break before the message
log.appendChild(messageDiv);
} else {
alert("No user login details found. Please log in.");
// Redirect to the login page or handle accordingly
}
///////////////////////////
///Leds Activation (Vision & Controller)
document.addEventListener('DOMContentLoaded', function() {
// Function to change color and text of the LED
window.changeColorAndText = function(ledId) {
console.log("Changing LED color and text...");
var led = document.getElementById(ledId);
if (!led) {
console.error("LED element not found.");
return;
}
var statusText = led.nextElementSibling;
// Toggle LED color and status text
if (led.classList.contains('green-light')) {
console.log("Changing LED to red...");
led.classList.remove('green-light');
led.classList.add('red-light');
localStorage.setItem('color', 'red');
statusText.textContent = 'FAULT';
} else {
console.log("Changing LED to green...");
led.classList.remove('red-light');
led.classList.add('green-light');
localStorage.setItem('color', 'green');
statusText.textContent = 'ACTIVE';
}
}
// Attach click event listeners to the LEDs
var leds = document.querySelectorAll('.circle');
if (!leds || leds.length === 0) {
console.error("No LEDs found.");
} else {
console.log("Attaching event listeners to LEDs...");
leds.forEach(function(led) {
led.addEventListener('click', function() {
console.log("LED clicked:", this.id);
changeColorAndText(this.id); // Pass the ID of the clicked LED
});
});
}
// Function to handle connect button click
function connectAndChangeLEDs() {
console.log("Connect button clicked.");
// Add your code here to handle connecting and changing LEDs
//find all divs whose onclick is changeColorAndText
var leds = document.querySelectorAll('.circle');
leds.forEach(function(led) {
changeColorAndText(led.id);
});
}
// Attach click event listener to the connect button
var connectButton = document.getElementById('disconnect');
if (!connectButton) {
console.error("Connect button not found.");
} else {
console.log("Attaching event listener to connect button...");
connectButton.addEventListener('click', connectAndChangeLEDs);
}
});
// /////////////////////////////////////////////////////////////
// Function to handle Connect button and Disconnect confirmation
function disconnectConfirm() {
var connectButton = document.getElementById("disconnect");
var modal = document.getElementById('myModal');
if (connectButton.textContent === "DISCONNECT") {
modal.style.display = 'block'; // Show modal for confirmation
} else {
connectButton.textContent = "DISCONNECT";
connectButton.style.backgroundColor = "green";
}
// Handle the disconnect action if confirmed
document.getElementById('yesButton').onclick = function() {
modal.style.display = 'none';
connectButton.textContent = "CONNECT";
connectButton.style.backgroundColor = "";
// Log the disconnect action or call logButtonClick('DISCONNECT')
logButtonClick('DISCONNECT');
}
// Close the modal if canceled
document.getElementById('noButton').onclick = function() {
modal.style.display = 'none';
}
// Close the modal if clicked outside the modal content
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = 'none';
}
}
// Close the modal if the close button is clicked
document.getElementsByClassName('close')[0].onclick = function() {
modal.style.display = 'none';
}
}
///////// /// Buttons Enabling code pressing Connect ///////
function enableButtons() {
var homingButton = document.getElementById('homing');
var clrfaultButton = document.getElementById('clrfault');
var resetallButton = document.getElementById('resetall');
var loadparamButton = document.getElementById('loadparam');
var proceedButton = document.getElementById('proceed');
// Enable the buttons
homingButton.disabled = false;
clrfaultButton.disabled = false;
resetallButton.disabled = false;
loadparamButton.disabled = false;
proceedButton.disabled = false;
}
/////////////////////////////////////////////////////////////////////
// Modal Code Behind Exit Button
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById('exit');
// Get the <span> element that closes the modal
var span1 = document.getElementsByClassName('close')[0];
// Get the Yes and No buttons
var yesButton = document.getElementById('yesButton');
var noButton = document.getElementById('noButton');
function handleExit() {
showModal(); // Display the modal
logEvent(); // Log the event
}
// Function to display the modal
function showModal() {
modal.style.display = 'block';
}
// Function to log the event in the log box
function logEvent() {
handleButtonClick('EXIT');
}
// When the user clicks on <span> (x), close the modal
span1.onclick = function() {
modal.style.display = 'none';
}
// When the user clicks on No, close the modal
noButton.onclick = function() {
modal.style.display = 'none';
}
// When the user clicks on Yes, close the modal and perform an action
yesButton.onclick = function() {
modal.style.display = 'none';
// Perform your action here, e.g., navigate away from the page
window.location.href = 'login.html';
history.back();
}
/////////////////////////////////////////////////////////////////////////
////Log Messsages on Button Click
function handleButtonClick(buttonName) {
// logButtonClick(buttonName);
var logBox = document.getElementById("log");
var currentTime = new Date();
var formattedTime = currentTime.toLocaleString();
var message = formattedTime + ": " + buttonName + " button clicked";
// Create a new div element for the log message
var logMessageDiv = document.createElement("div");
logMessageDiv.textContent = message;
// Append the new log message to the log box
logBox.appendChild(logMessageDiv);
}
///////////////////////////////////////////////////////////////////////////
// Function to save log to a file
function saveLogToFile() {
// Get log content
var logContent = document.getElementById('log').innerText;
console.log(logContent)
// Get current date and time
var currentDate = new Date();
var formattedDate = currentDate.toISOString().split('T')[0];
var formattedTime = currentDate.toTimeString().split(' ')[0].replace(/:/g, '-');
// Generate filename
var filename = formattedDate + '-' + formattedTime + '-' + 'username.elog';
// Create a Blob with the log content
var blob = new Blob([logContent], {type: 'text/plain'});
// Create a link element
var a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = filename;
// Append the link to the body
document.body.appendChild(a);
// Click the link to trigger the download
a.click();
// Remove the link
document.body.removeChild(a);
// Clear the log box
document.getElementById('log').innerText = '';
}
function showDatePicker() {
document.getElementById('datePicker').style.display = 'block';
}
// Function to handle date selection and open file browser
function selectDate() {
document.getElementById('datePicker').style.display = 'none';
// document.getElementById('logFileInput').style.display = 'block'; // Ensure the file input is visible
// document.getElementById('logFileInput').click(); // Trigger the click event on the file input to open the file browser
resetFileInputAndOpenBrowser();
}
// Function to reset file input
function resetFileInput() {
var fileInput = document.getElementById('logFileInput');
fileInput.value = ''; // Clear the file input
fileInput.style.display = 'none'; // Hide the file input after use
}
// Function to reset file input and open browser
function resetFileInputAndOpenBrowser() {
// Create a new file input element
var fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.style.display = 'none';
fileInput.onchange = handleFileSelect; // Attach the onchange handler
fileInput.id = 'logFileInput'; // Assign the same id to the new file input
// Replace the old file input with the new one
var oldFileInput = document.getElementById('logFileInput');
oldFileInput.parentNode.replaceChild(fileInput, oldFileInput);
// Trigger the click event on the new file input to open the file browser
fileInput.click();
}
var openedTab = null; // Track the opened tab
// Function to handle file selection and open in new tab
function handleFileSelect() {
const selectedFile = document.getElementById('logFileInput').files[0];
const reader = new FileReader();
reader.onload = function(e) {
// Extract the selected date from the date picker
const selectedDate = document.getElementById('datePicker').value;
const selectedDateString = new Date(selectedDate).toISOString().split('T')[0]; // Convert to ISO format
// Check if the selected file matches the selected date
if (selectedFile.name.endsWith('.elog')&&selectedFile.name.startsWith(selectedDateString)) {
// Open a new tab and display the file content
var openedTab = window.open();
openedTab.document.write('<pre>' + e.target.result + '</pre>');
} else {
// Display an error message if the file doesn't match the selected date
alert('Selected file does not match the selected date.');
}
// Reset the file input
resetFileInput();
// Hide the file browser
document.getElementById('fileBrowser').style.display = 'none';
};
reader.readAsText(selectedFile);
}
///////////////////////////////////////////////////////////////////
//Toggle Calander Function
function handleViewLog() {
handleButtonClick('VIEW LOG'); // Assuming this function works as intended
var datePicker = document.getElementById('datePicker');
if (datePicker.style.display === "none" || datePicker.style.display === "") {
datePicker.style.display = "block"; // Show the date picker
} else {
datePicker.style.display = "none"; // Hide the date picker
}
}
/////////////////////////////////////////////////////////////////////////////////////////
///Loading parameters file
/////////////////////////////////////////////////////////////////////////////////////////
// Function to handle the "LOAD PARAM" button click
function loadParameterFile() {
handleButtonClick('LOAD PARAMETER');
// Open file dialog
document.getElementById('paramFile').click();
}
// Event listener for file input change
document.getElementById('paramFile').addEventListener('change', handleFileSelect);
function handleFileSelect(event) {
const file = event.target.files[0];
if (file) {
if (file.name.endsWith('.param')) {
const reader = new FileReader();
reader.onload = function (e) {
try {
const params = JSON.parse(e.target.result);
enableProceedButton(params);
alert('File loaded successfully!');
console.log(params);
} catch (error) {
console.error('Invalid parameter file. File format mismatch:', error);
}
};
reader.readAsText(file);
} else {
alert('Please select a valid .param file.');
}
}
}
function enableProceedButton(params) {
const proceedButton = document.getElementById('proceed');
proceedButton.disabled = false;
proceedButton.addEventListener('click', function () {
// Construct the URL with parameters and redirect to next_page.html
const urlParams = new URLSearchParams();
urlParams.append('fPosx', params.fPosx);
urlParams.append('fPosy', params.fPosy);
urlParams.append('fPosz', params.fPosz);
urlParams.append('fOrientation', params.fOrientation);
urlParams.append('fRotation', params.fRotation);
urlParams.append('overLoop', params.overLoop);
urlParams.append('rpm', params.rpm);
// Replace 'next_page.html' with your actual next page
window.location.href = 'optscreen.html?' + urlParams.toString();
});
}
Here is complete detail.
thanks