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;









share|improve this question






















  • 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'); and res.send(JSON.stringify(data)); in your .post route.
    – chrisg86
    Nov 21 at 19:02















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;









share|improve this question






















  • 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'); and res.send(JSON.stringify(data)); in your .post route.
    – chrisg86
    Nov 21 at 19:02













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;









share|improve this question













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|improve this question













share|improve this question











share|improve this question




share|improve this question










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'); and res.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










  • 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
















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

















active

oldest

votes











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',
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
});


}
});














draft saved

draft discarded


















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






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

404 Error Contact Form 7 ajax form submitting

How to know if a Active Directory user can login interactively

Refactoring coordinates for Minecraft Pi buildings written in Python