I am trying to send data to front end of my app to create a graph. I attach the array in the response object but this doesn't work, although I can use the user value that is also sent in the response object on the front end.
var scoreQuery = "SELECT q1, q2, q3, q4, q5, q6, q7, q8, q1, q2, q3, q4 FROM table WHERE id = user.id";
var scoreArray;
module.exports = function(app, passport){
app.get('/profile', isLoggedIn, function (req, res) {
connection.query(scoreQuery, function (err, result, fields) {
if (err) throw err;
getData(result);
console.log(scoreArray);
}, res.render('profile.ejs', {
user:req.user,
data: scoreArray
})
);
});
};
function getData(result){
Object.keys(result).forEach(function(key) {
const values = result[key];
scoreArray = Object.values(values);
});
});
Below is the public/javascripts/scripts.js file where I'm creating the graph.
/*Scripts*/
var quizCategory1 = data.scoreArray.slice(0,7);
var quizCategory2 = data.scoreArray.slice(8,11);
var cat1Total = totalScore(category1);
var cat2Total = totalScore(category2);
function totalScore(categoryScore){
return categoryScore = scoreArray.reduce((accum,scoreArray) =>
{
const splitValues = scoreArray.split('/');
return {
score:accum.score + parseInt(splitValues[0]),
maxScore:accum.maxScore + parseInt(splitValues[1]),
}
},{score:0,maxScore:0}
);
}
var ctx = document.getElementById("myChart").getContext('2d');
var barTotalCategoryScores = [cat1Total.score, cat2Total.score];
var labels = ["Java & Design", "Build & Versioning"];
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: barTotalCategoryScores
}
}
});
the scoreArray prints out to the console whenever a user logsin so the sql query and getData() function are working. But when I try to use the data.scoreArray in my scripts.js file it doesn' work.