I am trying to show data from csv file into html using papa parse and js. I don’t want to show as a table, instead I want to show as a card using html and css styling but js can’t parse the csv. When I look at the console log, I don’t know why the results show html file when I clearly put the path as csv file.
My csv File:
image_path,name,description,price
/KMS/web-files/pop1.png,Product 1,This is the first product,10.99
/KMS/web-files/pop2.png,Product 2,This is the second product,12.49
/KMS/web-files/pop3.png,Product 3,This is the third product,8.99
My code:
<div class="row sectionBlockLayout text-start" style="display: flex; flex-wrap: wrap; margin: 0px; min-height: auto; padding: 8px; align-items: center; width: 1166px; right: 0;">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSV Data Display</title>
<style>
.card {
border: 1px solid #ccc;
padding: 16px;
margin: 8px;
text-align: center;
}
.card img {
max-width: 100px;
height: auto;
}
.price {
color: green;
font-weight: bold;
}
</style>
</head>
<body>
<div id="cards-container"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.0/papaparse.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
fetch('./data.csv')
.then(response => response.text())
.then(data => {
console.log('Raw CSV Data:', data); // Log the raw CSV data to see if it was fetched correctly
Papa.parse(data, {
header: true,
complete: function(results) {
console.log('Parsed CSV Data:', results.data); // Log the parsed data to see how it looks
const container = document.getElementById('cards-container');
results.data.forEach(row => {
console.log('Row:', row); // Log each row to see the structure
const card = document.createElement('div');
card.className = 'card';
const img = document.createElement('img');
img.src = row.image_path || 'default_image.jpg'; // Use a default image if image_path is missing
img.onerror = () => img.src = 'default_image.jpg'; // Fallback in case of broken image link
card.appendChild(img);
const name = document.createElement('h3');
name.textContent = row.name || 'No Name'; // Handle missing name
card.appendChild(name);
const description = document.createElement('p');
description.textContent = row.description || 'No Description'; // Handle missing description
card.appendChild(description);
const price = document.createElement('p');
price.className = 'price';
price.textContent = `$${row.price || '0.00'}`; // Handle missing price
card.appendChild(price);
container.appendChild(card);
});
},
error: function(error){
console.error('Parsing error: ', error.message);
}
});
})
.catch(error => console.error('Error fetching CSV:', error)); // Log any errors that occur during the fetch
});
</script>
</body>
</div>
This is my output