score:2
Accepted answer
event.preventdefault()
was missing at form submit:
the reason why your chart does not appear is because the event.preventdefault()
statement was missing in your form-submit. hence, your form was sending an http request (the default action) instead of executing your code.
i edited your code:
- added
event.preventdefault()
at form submit - declared variables outside functions in order to avoid re-declaring repeatedly
- eliminated the
async
functionality, asfetch()
is a promise (works like an async callback already, waiting for response from server) - re-aranged order:
first calldatatograph()
at form submit (withfetch()
for getting the data)
then, whenfetch()
-api returned the data (async), callgraphit()
- re-assign the data to your chart (x- and y-axis data) and top label and then
update()
the chart - adapted code for final version of chart.js v3.5.1 for improved performance (v3.x not compatible with v2.x):
- load initial data for italy with
datatograph()
run code snippet and enter a country ('italy', 'germany', ....)
(case-sensitive: first letter has to be capital letter)
// define all variables here outside functions
// in order to avoid re-assigning multiple times
let xs = [];
let ys = [];
let dataset = {};
dataset.xs = xs;
dataset.ys = ys;
let country = "italy";
let today = new date();
let dd = string(today.getdate()).padstart(2, '0');
let mm = string(today.getmonth() + 1).padstart(2, '0'); //january is 0!
let yyyy = today.getfullyear();
today = yyyy + '-' + mm + '-' + dd;
const delayinmilliseconds = 100000;
const ctx = document.getelementbyid('mychart').getcontext('2d');
const mychart = new chart(ctx, {
type: 'line',
data: {
labels: dataset.xs,
datasets: [{
label: `covid 19 confirmed cases in ${country}`,
data: dataset.ys,
backgroundcolor: ['rgba(255, 99, 132, 0.2)'],
bordercolor: ['rgba(255, 99, 132, 1)'],
borderwidth: 1,
fill: false,
}]
},
options: {
responsive: true,
maintainaspectratio: false,
scales: {
yaxes: { // <-- axis is not array '[{' anymore, now object '{'
scalelabel: {
display: true,
labelstring: 'confirmed cases'
}
},
xaxes: { // <-- axis is not array '[{' anymore, now object '{'
scalelabel: {
display: true,
labelstring: 'date'
}
}
}
}
});
// load initial data for italy
document.getelementbyid('country').value = country;
datatograph();
// here goes your event-listener with function as argument;
document.getelementbyid('country_form').addeventlistener('submit', datatograph);
function datatograph(event) {
if (event) event.preventdefault(); // <-- this was missing
country = document.getelementbyid('country').value;
// console.log("test 1", country);
// give feedback to user that data is loading in background
mychart.data.datasets[0].label = `loading ... ${country}`;
mychart.update();
// set all variables to empty again:
xs = [];
ys = [];
dataset = {};
dataset.xs = xs;
dataset.ys = ys;
// fetch() is a promise, i.e. it is like an async callback already,
// hence no need to call async again.
fetch(`https://webhooks.mongodb-stitch.com/api/client/v2.0/app/covid-19-qppza/service/rest-api/incoming_webhook/countries_summary?country=${country}&min_date=2020-04-22&max_date=${today}`)
.then(response => response.json())
.then(days => {
days.foreach(day => {
ys.push(day.confirmed);
xs.push(day.date);
});
dataset.xs = xs;
dataset.ys = ys;
// console.log("xs", xs);
// console.log("ys", ys);
// console.log(`https://webhooks.mongodb-stitch.com/api/client/v2.0/app/covid-19-qppza/service/rest-api/incoming_webhook/countries_summary?country=${country}&min_date=2020-04-22&max_date=${today}`);
// console.log(dataset);
// now you can graph it
graphit();
})
//return { xs, ys };
};
function graphit() {
document.getelementbyid('mychart').style.display = "block";
// const dataset = datatograph();
// console.log("dataset.xs", dataset.xs);
// console.log("dataset.ys", dataset.ys);
// re-assign the datasets again (x- and y-axis)
mychart.data.labels = dataset.xs;
mychart.data.datasets[0].data = dataset.ys;
mychart.data.datasets[0].label = `covid 19 confirmed cases in ${country}`;
// now update your chart
mychart.update();
};
<!-- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.3.0/chart.min.js"></script> -->
<!-- get the latest version of chart.js, now at v3.5.1 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div id="banner">
<div id="banner_details">
<h2>codata</h2>
</div>
</div>
<div id="one_line">
<div id="main_title">
<h1>covid-19 data</h1>
</div>
<div id="user_query_data">
<form id="country_form">
<input type="text" placeholder="country" id="country">
<input type="submit" value="search">
</form>
</div>
</div>
<div id="confirmed_graph">
<canvas id="mychart" height="500" width="300"></canvas>
</div>
final note:
you might consider to add the x: { type: 'time' ...
functionality to your chart, which would present the x-asis labels (dates) better. see my answer chart.js time series for more details.
by the way: nice api - i like it 👍
and welcome to stackoverflow
Source: stackoverflow.com
Related Query
- After form submit, function runs quickly and chart.js shows up for a second then goes away
- How to add second Y-axis for Bar and Line chart in Chart.js?
- Chart.js chart appears and disappears on form submit
- Problem for display a chart with Chart.js and Angular
- How to hide the y axis and x axis line and label in my bar chart for chart.js
- How to create a chart that uses strings for both the X and Y axes?
- How to draw outer labels for polar chart using ng2-charts and chart.js at fixed positions outside the rings?
- How to wait for all items to load within ng-repeat before then rendering a chart for each item
- How do I customize y-axis labels and randomly pick the value from the data range for x-axis in Chart js
- How can I have different values for the chart and the tooltip in chart.js?
- Charts js and laravel: Render chart after passing in json data
- Click on interactive chart.js bar chart and get value for labels and groups in JS
- Chart.js : Controller for Scatter chart doesn't work for draw function
- How do you set x and y axis and Title for a line chart using charts.js?
- Why chart renders after second click - react-chartjs-2
- Charts JS: Doughnut chart and hiding tooltip for specific data index within each dataset
- Resetting transform: rotate() by removing and appending canvas not showing data after appending and redrawing chart
- chart.js Second hidden value for Bar Chart
- Chart Piechart in only show percentage on hover but it shows data and label with percentage both i just want to show percentage only percentage
- How to show symbols after the label and before the numeric value using chart.js Bar chart in Angular
- How to start the chart from specific time and offest hour and then show the data on chart from target datetime in chartjs
- How do i have a single Chart.vue component instead of different chart components and then display charts from it by changing id of the API
- attempting to change height and width of canvas for chart
- VueJS + Chartjs - Chart only renders after code change
- calling a function for fontSize in Doughnut Chart (typescript)
- Update chart.js after form submission and page reload
- getting additional value fields from data source for dx.chartjs doughnut chart
- I am using chart js to draw a chart. I did everything right but i don't know why the x axis and y axis label is not comming in chart. code below
- Frontend and backend for chart using chartjs, mongodb, and controller
- Line chart plotting multiple points for duplicate data on x and y axis using chart.js
More Query from same tag
- How to access global variable from outside of canvas.onmousemove function?
- Chart.js line chart: gap between December and January
- Customize different tooltips of bar chart
- Chart.js - Horizontal line on Bar chart interferes with tooltip
- Using Datalabels and ChartJS with Chartjs-node-canvas
- Chart.js coming up as blank
- Chart.js Stacked Group Bar model after updating version Chart.js 2.9.4 -> Chart.js 3.5.0
- How to convert an array of strings to float in Javascript
- Chart.js not updating multiple charts independently
- Chart Js Change Label orientation on x-Axis for Line Charts
- Hide Y-axis labels when data is not displayed in Chart.js
- Chart.js place y value position and its x-label position relative to the x-value
- Chart.js pie chart to display "No Data" if the datasets are empty
- Chartjs: How to offset ticks on radarchart?
- Chart.js extremely slow on 8 series of 500+ points
- Chart.js set Doughnut background-color?
- Displaying two values in tooltip using chart.js
- Chart.js 3.6.2, Angular 10: Logarithmic Line chart Y-Axis problems. How to set and keep Y-Axis properties, even when data changes?
- Data will not draw onto my chart
- Time graphs chart.js
- No chart appears - Chart.js
- Vue js component and Chart js
- Changing Chart.js chart type doesn't remove older axis
- Links in bar charts (charts.js)
- How to plot a single value with line in line chart graph using charts.js?
- Populate colors on a Chart.js chart dynamically
- Displaying JSON in Chart.js
- Legend not displaying on Line or Bar chart - React-Chartjs-2
- ChartJs x axis labels on waterfall chart
- react-chartjs-2 Line Chart not updating with State