35846-vm/assets/js/main.js
2025-11-19 12:21:30 +00:00

95 lines
3.3 KiB
JavaScript

document.addEventListener('DOMContentLoaded', function () {
const dropZone = document.getElementById('drop-zone');
const fileInput = document.getElementById('csv-file');
const fileNameDisplay = document.getElementById('file-name-display');
const uploadForm = document.getElementById('upload-form');
const resultsSection = document.getElementById('results-section');
const analysisOutput = document.getElementById('analysis-output');
const submitButton = uploadForm.querySelector('button[type="submit"]');
const spinner = submitButton.querySelector('.spinner-border');
// Open file dialog when drop zone is clicked
dropZone.addEventListener('click', () => fileInput.click());
// Drag and drop events
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
dropZone.classList.add('drag-over');
});
dropZone.addEventListener('dragleave', () => {
dropZone.classList.remove('drag-over');
});
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('drag-over');
const files = e.dataTransfer.files;
if (files.length > 0) {
fileInput.files = files;
updateFileName();
}
});
// Update file name display on change
fileInput.addEventListener('change', updateFileName);
function updateFileName() {
if (fileInput.files.length > 0) {
fileNameDisplay.textContent = fileInput.files[0].name;
} else {
fileNameDisplay.textContent = 'No file selected';
}
}
// Handle form submission
uploadForm.addEventListener('submit', function (e) {
e.preventDefault();
if (fileInput.files.length === 0) {
alert('Please select a CSV file to analyze.');
return;
}
// Show spinner and disable button
spinner.classList.remove('d-none');
submitButton.disabled = true;
const formData = new FormData(uploadForm);
// Show loading state
resultsSection.style.display = 'block';
analysisOutput.innerHTML = `
<div class="text-center p-5">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-3">AI is analyzing your data, this may take a moment...</p>
</div>
`;
resultsSection.scrollIntoView({ behavior: 'smooth' });
fetch('upload.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
analysisOutput.innerHTML = data.analysis;
} else {
analysisOutput.innerHTML = `<div class="alert alert-danger">${data.error || 'An unknown error occurred.'}</div>`;
}
})
.catch(error => {
console.error('Error:', error);
analysisOutput.innerHTML = `<div class="alert alert-danger">An error occurred while communicating with the server.</div>`;
})
.finally(() => {
// Hide spinner and re-enable button
spinner.classList.add('d-none');
submitButton.disabled = false;
});
});
});