Trying to populate Chart.js graph with fetch() response data
up vote
0
down vote
favorite
So i have a chartjs graph. When a button is clicked, I use fetch()
to grab data from the node server. web server sends the data i.e. an array
to the browser.
Problem: it's not populating the graph with fetch() response
-> As defined in myscript.js
client-side file.
I should be able to do this without a template engine right? What am I doing here please help.
node server api - index.js
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) {
data = [100, 200, 150, 100];
} else {
data = [0, 0, 0, 0];
}
console.log(req.name);
res.send(data);
});
module.exports = router;
clientside javascript - myscript.js i.e. fetch()
// 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;
// event.defaultPrevented();
// give endpoint, and create a request to send
fetch("/", {
method: 'POST',
headers: new Headers(),
body: JSON.stringify({ name: name})
}).then(function(response) {
return response.json();
}).then(function(myJson) {
if(myJson !== null)
populateGraph(myJson);
console.log("populated data.")
});
});
var ctx = document.getElementById("myChart");
function populateGraph(db_data) {
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: db_data,
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
}
}]
}
}
});
}
index.html
<html>
<head>
<title>Express</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<header>
<h1>Express</h1>
<p>Welcome to Express</p>
</header>
<section class="section-one">
<div class="graph-wrap">
<canvas id="myChart"></canvas>
</div>
<form id="form" method="POST">
<input type="text" id="form-name" name="name" value="shahyan">
<button type="submit">ACTIVATE</button>
</form>
</section>
<script src="/javascripts/Chart.js"></script>
<script src="/javascripts/myscript.js"></script>
</body>
</html>
app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Adding the path to chartjs to the public/scripts folder
app.use('/javascripts', express.static(__dirname + '/node_modules/chart.js/dist/'));
app.use('/', indexRouter);
app.use('/users', usersRouter);
module.exports = app;
javascript node.js chart.js fetch
add a comment |
up vote
0
down vote
favorite
So i have a chartjs graph. When a button is clicked, I use fetch()
to grab data from the node server. web server sends the data i.e. an array
to the browser.
Problem: it's not populating the graph with fetch() response
-> As defined in myscript.js
client-side file.
I should be able to do this without a template engine right? What am I doing here please help.
node server api - index.js
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) {
data = [100, 200, 150, 100];
} else {
data = [0, 0, 0, 0];
}
console.log(req.name);
res.send(data);
});
module.exports = router;
clientside javascript - myscript.js i.e. fetch()
// 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;
// event.defaultPrevented();
// give endpoint, and create a request to send
fetch("/", {
method: 'POST',
headers: new Headers(),
body: JSON.stringify({ name: name})
}).then(function(response) {
return response.json();
}).then(function(myJson) {
if(myJson !== null)
populateGraph(myJson);
console.log("populated data.")
});
});
var ctx = document.getElementById("myChart");
function populateGraph(db_data) {
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: db_data,
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
}
}]
}
}
});
}
index.html
<html>
<head>
<title>Express</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<header>
<h1>Express</h1>
<p>Welcome to Express</p>
</header>
<section class="section-one">
<div class="graph-wrap">
<canvas id="myChart"></canvas>
</div>
<form id="form" method="POST">
<input type="text" id="form-name" name="name" value="shahyan">
<button type="submit">ACTIVATE</button>
</form>
</section>
<script src="/javascripts/Chart.js"></script>
<script src="/javascripts/myscript.js"></script>
</body>
</html>
app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Adding the path to chartjs to the public/scripts folder
app.use('/javascripts', express.static(__dirname + '/node_modules/chart.js/dist/'));
app.use('/', indexRouter);
app.use('/users', usersRouter);
module.exports = app;
javascript node.js chart.js fetch
share structure of data received from server
– front_end_dev
Nov 20 at 7:20
res.send(data) returns this on screen [100,200,150,100]
– Shaz
Nov 20 at 7:47
You should probably send appropriate headers for json and the json stringified array:res.setHeader('Content-Type', 'application/json');
andres.send(JSON.stringify(data));
in your.post
route.
– chrisg86
Nov 21 at 19:02
add a comment |
up vote
0
down vote
favorite
up vote
0
down vote
favorite
So i have a chartjs graph. When a button is clicked, I use fetch()
to grab data from the node server. web server sends the data i.e. an array
to the browser.
Problem: it's not populating the graph with fetch() response
-> As defined in myscript.js
client-side file.
I should be able to do this without a template engine right? What am I doing here please help.
node server api - index.js
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) {
data = [100, 200, 150, 100];
} else {
data = [0, 0, 0, 0];
}
console.log(req.name);
res.send(data);
});
module.exports = router;
clientside javascript - myscript.js i.e. fetch()
// 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;
// event.defaultPrevented();
// give endpoint, and create a request to send
fetch("/", {
method: 'POST',
headers: new Headers(),
body: JSON.stringify({ name: name})
}).then(function(response) {
return response.json();
}).then(function(myJson) {
if(myJson !== null)
populateGraph(myJson);
console.log("populated data.")
});
});
var ctx = document.getElementById("myChart");
function populateGraph(db_data) {
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: db_data,
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
}
}]
}
}
});
}
index.html
<html>
<head>
<title>Express</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<header>
<h1>Express</h1>
<p>Welcome to Express</p>
</header>
<section class="section-one">
<div class="graph-wrap">
<canvas id="myChart"></canvas>
</div>
<form id="form" method="POST">
<input type="text" id="form-name" name="name" value="shahyan">
<button type="submit">ACTIVATE</button>
</form>
</section>
<script src="/javascripts/Chart.js"></script>
<script src="/javascripts/myscript.js"></script>
</body>
</html>
app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Adding the path to chartjs to the public/scripts folder
app.use('/javascripts', express.static(__dirname + '/node_modules/chart.js/dist/'));
app.use('/', indexRouter);
app.use('/users', usersRouter);
module.exports = app;
javascript node.js chart.js fetch
So i have a chartjs graph. When a button is clicked, I use fetch()
to grab data from the node server. web server sends the data i.e. an array
to the browser.
Problem: it's not populating the graph with fetch() response
-> As defined in myscript.js
client-side file.
I should be able to do this without a template engine right? What am I doing here please help.
node server api - index.js
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) {
data = [100, 200, 150, 100];
} else {
data = [0, 0, 0, 0];
}
console.log(req.name);
res.send(data);
});
module.exports = router;
clientside javascript - myscript.js i.e. fetch()
// 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;
// event.defaultPrevented();
// give endpoint, and create a request to send
fetch("/", {
method: 'POST',
headers: new Headers(),
body: JSON.stringify({ name: name})
}).then(function(response) {
return response.json();
}).then(function(myJson) {
if(myJson !== null)
populateGraph(myJson);
console.log("populated data.")
});
});
var ctx = document.getElementById("myChart");
function populateGraph(db_data) {
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: db_data,
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
}
}]
}
}
});
}
index.html
<html>
<head>
<title>Express</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<header>
<h1>Express</h1>
<p>Welcome to Express</p>
</header>
<section class="section-one">
<div class="graph-wrap">
<canvas id="myChart"></canvas>
</div>
<form id="form" method="POST">
<input type="text" id="form-name" name="name" value="shahyan">
<button type="submit">ACTIVATE</button>
</form>
</section>
<script src="/javascripts/Chart.js"></script>
<script src="/javascripts/myscript.js"></script>
</body>
</html>
app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Adding the path to chartjs to the public/scripts folder
app.use('/javascripts', express.static(__dirname + '/node_modules/chart.js/dist/'));
app.use('/', indexRouter);
app.use('/users', usersRouter);
module.exports = app;
javascript node.js chart.js fetch
javascript node.js chart.js fetch
asked Nov 20 at 7:11
Shaz
522617
522617
share structure of data received from server
– front_end_dev
Nov 20 at 7:20
res.send(data) returns this on screen [100,200,150,100]
– Shaz
Nov 20 at 7:47
You should probably send appropriate headers for json and the json stringified array:res.setHeader('Content-Type', 'application/json');
andres.send(JSON.stringify(data));
in your.post
route.
– chrisg86
Nov 21 at 19:02
add a comment |
share structure of data received from server
– front_end_dev
Nov 20 at 7:20
res.send(data) returns this on screen [100,200,150,100]
– Shaz
Nov 20 at 7:47
You should probably send appropriate headers for json and the json stringified array:res.setHeader('Content-Type', 'application/json');
andres.send(JSON.stringify(data));
in your.post
route.
– chrisg86
Nov 21 at 19:02
share structure of data received from server
– front_end_dev
Nov 20 at 7:20
share structure of data received from server
– front_end_dev
Nov 20 at 7:20
res.send(data) returns this on screen [100,200,150,100]
– Shaz
Nov 20 at 7:47
res.send(data) returns this on screen [100,200,150,100]
– Shaz
Nov 20 at 7:47
You should probably send appropriate headers for json and the json stringified array:
res.setHeader('Content-Type', 'application/json');
and res.send(JSON.stringify(data));
in your .post
route.– chrisg86
Nov 21 at 19:02
You should probably send appropriate headers for json and the json stringified array:
res.setHeader('Content-Type', 'application/json');
and res.send(JSON.stringify(data));
in your .post
route.– chrisg86
Nov 21 at 19:02
add a comment |
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
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%2f53387939%2ftrying-to-populate-chart-js-graph-with-fetch-response-data%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
share structure of data received from server
– front_end_dev
Nov 20 at 7:20
res.send(data) returns this on screen [100,200,150,100]
– Shaz
Nov 20 at 7:47
You should probably send appropriate headers for json and the json stringified array:
res.setHeader('Content-Type', 'application/json');
andres.send(JSON.stringify(data));
in your.post
route.– chrisg86
Nov 21 at 19:02