-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathapp.js
56 lines (45 loc) · 1.69 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Select the form and file input elements
const form = document.getElementById('csvUploadForm');
const responseMessage = document.getElementById('uploadResponse');
// Add an event listener to handle form submission
form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent default form submission
const fileInput = document.getElementById('csvFile');
const file = fileInput.files[0];
if (!file) {
responseMessage.innerText = 'Please upload a CSV file.';
return;
}
// Read and process the CSV file
const reader = new FileReader();
reader.onload = async function(e) {
const csvContent = e.target.result;
const parsedData = processCSV(csvContent);
// Send the parsed data to a mock API endpoint
try {
const response = await fetch('https://mockapi.example.com/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(parsedData),
});
if (!response.ok) {
throw new Error('Failed to submit CSV data');
}
const result = await response.json();
responseMessage.innerText = 'File uploaded and processed successfully: ' + result.message;
} catch (error) {
responseMessage.innerText = 'Error: ' + error.message;
}
};
reader.readAsText(file); // Read the CSV file
});
// Function to process the CSV content
function processCSV(csvContent) {
const rows = csvContent.split('\n');
const data = rows.map(row => row.split(','));
// Example cleaning: Remove rows with empty cells
const cleanedData = data.filter(row => row.every(cell => cell.trim() !== ''));
return cleanedData; // Return cleaned CSV data
}