Chartjs-NODEJS API: How to render .pug and send a AJAX response at same time?

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()

Leave a comment