2

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.

suspense_hey
  • 85
  • 2
  • 11

3 Answers3

1

Add new route:

app.get('/profile/:id', (req,res) => {
    // your_array = query DB with param id (req.params.id) store in your array
    res.status(200).json({data: <your_array>})
})

Then on your client make a GET query on /profile/:id (https://developer.mozilla.org/fr/docs/Web/API/XMLHttpRequest) when the page loading (window.onload)


For MySQL, you should using :

Acolyte
  • 91
  • 1
  • 5
  • Thanks for your help : ) How and where would you implement the get query on the client side? I'm a beginner. – suspense_hey May 16 '19 at 15:19
  • also, i don't actually understand this // your_array = query DB with param id (req.params.id) store in your array is is the DB query I have at the top, var scoreQuery? and what does the :id refer to? – suspense_hey May 16 '19 at 15:21
  • you_array it's the data you need for your client (scoreArray) For client side check this : https://stackoverflow.com/questions/1973140/parsing-json-from-xmlhttprequest-responsejson – Acolyte May 16 '19 at 15:27
  • Sorry, I really don't understand what this means " (req.params.id) store in your array ". – suspense_hey May 16 '19 at 17:33
  • req is your request object, contains the param /:id (express) – Acolyte May 17 '19 at 05:51
1

server :


// ... your routes


// + new route
app.get('/profile/:id', (req,res) => {
     let id = req.params.id // e.g /profile/3 -> req.params.id = 3
     let scoreArray;

     // your query (it's very bad to set param in your query like this (injection SQL) )
     let scoreQuery = `SELECT q1, q2, q3, q4, q5, q6, q7, q8, q1, q2, q3, q4 FROM 
     table WHERE id = ${id}`;  // `... ${foo}` => https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Litt%C3%A9raux_gabarits

     connection.query(scoreQuery, function (err, result, fields) {
                if (err) throw err;
                getData(result);
                console.log(scoreArray);
             }, res.status(200).json({
                user:req.user,
                data: scoreArray
            })
        );
 })

// ... your method

function getData(result){
    Object.keys(result).forEach(function(key) {
        const values = result[key];
        scoreArray = Object.values(values);
    });
});

client :

/* code to get data
 let id_test = 1;

  fetch(`http://localhost:<your_node_server_port>/profil/${id_test}`)
  .then(response => response.json())
  .then(json => console.log(json)) // return profil for id 1
*/

// e.g page is loaded
window.onload = () => {
  let id_test = 1;

  fetch(`http://localhost:<your_node_server_port>/profil/${id_test}`)
  .then(response => response.json())
  .then(json => console.log(json)) // return profil for id 1
}
Acolyte
  • 91
  • 1
  • 5
0

Thanks a million Sylvain, your explanation got me on the right track. I did the following...

//routes.js

    app.get('/profile',  function (req, res) {
        let id = req.user.id;
        getData(id, function (score) {
            res.status(200).render('profile.ejs',{user: req.user, score})
        });
    });

I put my sql statement within the getData() function and used a '?' in place of id in my sql statement and send id parameter as value to insert into the query method. This has has worked and I can now get the score object on the client-side ejs file using <?= score.cat1Total.score ?>.

My problem now is still trying to use score.cat1Total.score in my public/javascripts/scripts.js file and it is undefined... and I'm not sure how to correctly implement your window.onload() method

// /public/javascripts/scripts.js 

/* code to get data?
window.onload = () => {
  fetch(`http://localhost:8080/profile)
  .then(response => response.json())
  .then(json => console.log(json)) 
}
*/

var ctx = document.getElementById("myChart").getContext('2d');

//This is where I am trying to get score objects values. 
var barTotalCategoryScores = [score.cat1Total.score, cat2Total.score];

var labels = ["Java & Design", "Build & Versioning"];

var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: labels,
        datasets: barTotalCategoryScores
          }
    }
});

FYI below is the getData(id, callback) method I used in routes

// routes.js

function getData(id, callback) {

    let scoreQuery = "SELECT c1q1, c1q2, c1q3, c1q4, c1q5, c1q6, c1q7, c1q8, c2q1, c2q2, c2q3, c2q4 FROM nodejs_login.assessment_score AS a JOIN nodejs_login.users as u ON a.respondent_id = u.user_respondent_id WHERE a.respondent_id = ?";

    connection.query(scoreQuery, [id],function (err, result) {
        if (err) throw err;

        Object.keys(result).forEach(function(key) {
            let values = result[key];
            let scoreArray = Object.values(values);

            let category1 = scoreArray.slice(0,7);
            let category2 = scoreArray.slice(8,11);

            //parsing and accumlating each category score
            var cat1Total = totalScore(category1);
            var cat2Total = totalScore(category2);


            //function to parse the strings into numbers and accumulate them
            function totalScore(categoryScore){
                return categoryScore.reduce((accum,scoreArray) =>
                    {
                        const splitValues = scoreArray.split('/');
                        return {
                            score:accum.score + parseInt(splitValues[0]),
                            maxScore:accum.maxScore + parseInt(splitValues[1]),
                        }
                    },{score:0,maxScore:0}
                );
            }
            let categories = {cat1Total, cat2Total};

            callback(categories);

        });
    })
}
suspense_hey
  • 85
  • 2
  • 11