2š
I donāt see the code that actually gets rendered by the server, but if your form contains action attribute, then you need to prevent its default behaviour on submit. To do that, modify your āsubmitā event listener callback:
document.getElementById("form").addEventListener("submit", function(event) {
event.preventDefault(); // don't execute default browser's behaviour
// rest of your code goes here
});
Now there might be multiple reasons on why your chart does not update. For starters, instead of using res.send() in your node API, use res.json() ā this way your server will send data in json format. Also, I would move this lineā¦
var ctx = document.getElementById("myChart");
ā¦to the populateGraph function to make it self sufficient.
Finally, keep in mind that by using
myChart.data.datasets[0].data.push(myJson.myData);
Youāre actually adding values to the datasetās data array. So values for the labels on your chart will be:
Red: 0
Blue: 0
Yellow: 0
Green: 100
Purple: 200
Orange: 150
Last number (100) will not get assigned to any label.
On the side note, POST request should be used to send data for the server, not to obtain them. I know that youāre probably just experimenting with express, but when you design an API, it should serve the data as a response to the GET request.
For the future, itās good idea to keep the server rendering the page and the API separate.
0š
You could either have two separate backend endpoints for JSON and a regular templates, or send āContent-typeā: āapplication/jsonā header in you client-side fetch
and then check for this header in the server-side code. If the header is present, you can then response with res.json()
instead if res.send()