I try to find a way to use data from txt file into chart.js graphic. I'm not very friendly with JS so I ask some help... So, what I succeed was to build a beautifull simple graph using this code :
<canvas id="myChart" style="width:100%;max-width:900px"></canvas>
<script>
const xValues = [50,60,70,80,90,100,110,120,130,140,150];
const yValues = [7,8,8,9,9,9,10,11,14,14,15];
new Chart("myChart", {
type: "line",
data: {
labels: xValues,
datasets: [{
fill: false,
lineTension: 0,
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: yValues
}]
},
options: {
legend: {display: false},
scales: {
yAxes: [{ticks: {min: 6, max:16}}],
}
}
});
</script>
But now I would like to replace xValues and yValues with data from txt file. What could be the best solution ? I tries some code with " $.get('/staticFiles/xValues.txt', " but it didn't work, as I said I'm not very friendly with JS ..
If somebody could tell me if an easy tuto may exist . Thank you so much.
No need for jQuery
Assuming running on an HTML server and assuming one text file called data.txt in the same folder as your HTML with the lines
50,60,70,80,90,100,110,120,130,140,150
7,8,8,9,9,9,10,11,14,14,15
you can do
document.addEventListener('DOMContentLoaded', () => {
fetch('data.txt')
.then(response => response.text())
.then(text => {
const lines = text.split('\n');
const xValues = lines[0].split(',').map(Number);
const yValues = lines[1].split(',').map(Number);
new Chart("myChart", {
type: "line",
data: {
labels: xValues,
datasets: [{
fill: false,
lineTension: 0,
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: yValues
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
min: 6,
max: 16
}
}],
}
}
});
})
.catch(error => {
console.error('Error fetching data', error);
});
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" style="width:100%;max-width:900px"></canvas>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With