NODEJS API: How to render .pug and send a AJAX response at same time?
I am trying to dynamically update Chart.js graph with data coming from a web server via fetch() request e.g.
res.send({myData: data});
Problem is: res.send() deletes the pug template on the browser. What is the best way to populate the chart with fetch() response while rendering the template on screen?
index.js - NODE API
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/', function(req, res, next) {
if(req.body.name) {
console.log(req.body.name);
data = [100, 200, 150, 100];
} else {
data = [0, 0, 0, 0];
}
res.send({myData: data});
// res.render('index', { graph_data: data });
});
module.exports = router;
myscript.js - client script with ajax request
// make an ajax fetch request to the server for graph data and populate it.
document.getElementById("form").addEventListener("submit", function(event) {
// get for inputs to send to server
let name = document.getElementById("form-name").value;
console.log("fetch...");
// event.defaultPrevented();
// give endpoint, and create a request to send
fetch("/", {
method: 'POST',
headers: new Headers(),
body: JSON.stringify({ name: name})
}).then(function(response) {
console.log("response returned..")
return response.json();
}).then(function(myJson) {
console.log("populated data.")
populateGraph(myJson);
});
});
console.log("populated data.")
var ctx = document.getElementById("myChart");
function populateGraph(myJson) {
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [0, 0, 0],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
responsive:true,
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
myChart.data.datasets[0].data.push(myJson.myData);
myChart.update();
}
Any ideas on how to make this work?
javascript node.js ajax chart.js fetch
add a comment |
I am trying to dynamically update Chart.js graph with data coming from a web server via fetch() request e.g.
res.send({myData: data});
Problem is: res.send() deletes the pug template on the browser. What is the best way to populate the chart with fetch() response while rendering the template on screen?
index.js - NODE API
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/', function(req, res, next) {
if(req.body.name) {
console.log(req.body.name);
data = [100, 200, 150, 100];
} else {
data = [0, 0, 0, 0];
}
res.send({myData: data});
// res.render('index', { graph_data: data });
});
module.exports = router;
myscript.js - client script with ajax request
// make an ajax fetch request to the server for graph data and populate it.
document.getElementById("form").addEventListener("submit", function(event) {
// get for inputs to send to server
let name = document.getElementById("form-name").value;
console.log("fetch...");
// event.defaultPrevented();
// give endpoint, and create a request to send
fetch("/", {
method: 'POST',
headers: new Headers(),
body: JSON.stringify({ name: name})
}).then(function(response) {
console.log("response returned..")
return response.json();
}).then(function(myJson) {
console.log("populated data.")
populateGraph(myJson);
});
});
console.log("populated data.")
var ctx = document.getElementById("myChart");
function populateGraph(myJson) {
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [0, 0, 0],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
responsive:true,
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
myChart.data.datasets[0].data.push(myJson.myData);
myChart.update();
}
Any ideas on how to make this work?
javascript node.js ajax chart.js fetch
add a comment |
I am trying to dynamically update Chart.js graph with data coming from a web server via fetch() request e.g.
res.send({myData: data});
Problem is: res.send() deletes the pug template on the browser. What is the best way to populate the chart with fetch() response while rendering the template on screen?
index.js - NODE API
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/', function(req, res, next) {
if(req.body.name) {
console.log(req.body.name);
data = [100, 200, 150, 100];
} else {
data = [0, 0, 0, 0];
}
res.send({myData: data});
// res.render('index', { graph_data: data });
});
module.exports = router;
myscript.js - client script with ajax request
// make an ajax fetch request to the server for graph data and populate it.
document.getElementById("form").addEventListener("submit", function(event) {
// get for inputs to send to server
let name = document.getElementById("form-name").value;
console.log("fetch...");
// event.defaultPrevented();
// give endpoint, and create a request to send
fetch("/", {
method: 'POST',
headers: new Headers(),
body: JSON.stringify({ name: name})
}).then(function(response) {
console.log("response returned..")
return response.json();
}).then(function(myJson) {
console.log("populated data.")
populateGraph(myJson);
});
});
console.log("populated data.")
var ctx = document.getElementById("myChart");
function populateGraph(myJson) {
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [0, 0, 0],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
responsive:true,
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
myChart.data.datasets[0].data.push(myJson.myData);
myChart.update();
}
Any ideas on how to make this work?
javascript node.js ajax chart.js fetch
I am trying to dynamically update Chart.js graph with data coming from a web server via fetch() request e.g.
res.send({myData: data});
Problem is: res.send() deletes the pug template on the browser. What is the best way to populate the chart with fetch() response while rendering the template on screen?
index.js - NODE API
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/', function(req, res, next) {
if(req.body.name) {
console.log(req.body.name);
data = [100, 200, 150, 100];
} else {
data = [0, 0, 0, 0];
}
res.send({myData: data});
// res.render('index', { graph_data: data });
});
module.exports = router;
myscript.js - client script with ajax request
// make an ajax fetch request to the server for graph data and populate it.
document.getElementById("form").addEventListener("submit", function(event) {
// get for inputs to send to server
let name = document.getElementById("form-name").value;
console.log("fetch...");
// event.defaultPrevented();
// give endpoint, and create a request to send
fetch("/", {
method: 'POST',
headers: new Headers(),
body: JSON.stringify({ name: name})
}).then(function(response) {
console.log("response returned..")
return response.json();
}).then(function(myJson) {
console.log("populated data.")
populateGraph(myJson);
});
});
console.log("populated data.")
var ctx = document.getElementById("myChart");
function populateGraph(myJson) {
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [0, 0, 0],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
responsive:true,
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
myChart.data.datasets[0].data.push(myJson.myData);
myChart.update();
}
Any ideas on how to make this work?
javascript node.js ajax chart.js fetch
javascript node.js ajax chart.js fetch
asked Nov 20 at 8:34
Shaz
524617
524617
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
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.
That was the reason the graph wasn't showing!
– Shaz
Nov 20 at 9:05
However the chartjs is not updating
– Shaz
Nov 20 at 9:06
I've edited the answer - additional information should help you to solve the problem with chart not rendering.
– rufus1530
Nov 20 at 9:30
add a comment |
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()
An example code of what you mean would be nice, I don't understand
– Shaz
Nov 20 at 9:01
You could start with replacingres.send({myData: data});withres.json({myData: data});, in your Node index.js, there is a chane that it could be enough
– Anton Pastukhov
Nov 20 at 9:04
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389005%2fnodejs-api-how-to-render-pug-and-send-a-ajax-response-at-same-time%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
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.
That was the reason the graph wasn't showing!
– Shaz
Nov 20 at 9:05
However the chartjs is not updating
– Shaz
Nov 20 at 9:06
I've edited the answer - additional information should help you to solve the problem with chart not rendering.
– rufus1530
Nov 20 at 9:30
add a comment |
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.
That was the reason the graph wasn't showing!
– Shaz
Nov 20 at 9:05
However the chartjs is not updating
– Shaz
Nov 20 at 9:06
I've edited the answer - additional information should help you to solve the problem with chart not rendering.
– rufus1530
Nov 20 at 9:30
add a comment |
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.
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.
edited Nov 20 at 9:28
answered Nov 20 at 8:52
rufus1530
396111
396111
That was the reason the graph wasn't showing!
– Shaz
Nov 20 at 9:05
However the chartjs is not updating
– Shaz
Nov 20 at 9:06
I've edited the answer - additional information should help you to solve the problem with chart not rendering.
– rufus1530
Nov 20 at 9:30
add a comment |
That was the reason the graph wasn't showing!
– Shaz
Nov 20 at 9:05
However the chartjs is not updating
– Shaz
Nov 20 at 9:06
I've edited the answer - additional information should help you to solve the problem with chart not rendering.
– rufus1530
Nov 20 at 9:30
That was the reason the graph wasn't showing!
– Shaz
Nov 20 at 9:05
That was the reason the graph wasn't showing!
– Shaz
Nov 20 at 9:05
However the chartjs is not updating
– Shaz
Nov 20 at 9:06
However the chartjs is not updating
– Shaz
Nov 20 at 9:06
I've edited the answer - additional information should help you to solve the problem with chart not rendering.
– rufus1530
Nov 20 at 9:30
I've edited the answer - additional information should help you to solve the problem with chart not rendering.
– rufus1530
Nov 20 at 9:30
add a comment |
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()
An example code of what you mean would be nice, I don't understand
– Shaz
Nov 20 at 9:01
You could start with replacingres.send({myData: data});withres.json({myData: data});, in your Node index.js, there is a chane that it could be enough
– Anton Pastukhov
Nov 20 at 9:04
add a comment |
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()
An example code of what you mean would be nice, I don't understand
– Shaz
Nov 20 at 9:01
You could start with replacingres.send({myData: data});withres.json({myData: data});, in your Node index.js, there is a chane that it could be enough
– Anton Pastukhov
Nov 20 at 9:04
add a comment |
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()
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()
answered Nov 20 at 8:56
Anton Pastukhov
1978
1978
An example code of what you mean would be nice, I don't understand
– Shaz
Nov 20 at 9:01
You could start with replacingres.send({myData: data});withres.json({myData: data});, in your Node index.js, there is a chane that it could be enough
– Anton Pastukhov
Nov 20 at 9:04
add a comment |
An example code of what you mean would be nice, I don't understand
– Shaz
Nov 20 at 9:01
You could start with replacingres.send({myData: data});withres.json({myData: data});, in your Node index.js, there is a chane that it could be enough
– Anton Pastukhov
Nov 20 at 9:04
An example code of what you mean would be nice, I don't understand
– Shaz
Nov 20 at 9:01
An example code of what you mean would be nice, I don't understand
– Shaz
Nov 20 at 9:01
You could start with replacing
res.send({myData: data}); with res.json({myData: data});, in your Node index.js, there is a chane that it could be enough– Anton Pastukhov
Nov 20 at 9:04
You could start with replacing
res.send({myData: data}); with res.json({myData: data});, in your Node index.js, there is a chane that it could be enough– Anton Pastukhov
Nov 20 at 9:04
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389005%2fnodejs-api-how-to-render-pug-and-send-a-ajax-response-at-same-time%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown