Hello, it is necessary to transfer an array from the server (nodejs) to the client in order to build a graph using it. I pass an array, but on the client it says that it is not an array. Where is the error in the code?

Server:

app.post('/averageTimeInQueue', function(req, res, next) { var data = [ [2012, 1000, 400, 232], [2005, 1170, 460, 421], [2006, 660, 1120, 4324] ]; res.send(data); }); 

Customer:

 google.charts.load('current', {'packages':['line']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('number', 'Day'); data.addColumn('number', 'Guardians of the Galaxy'); data.addColumn('number', 'The Avengers'); data.addColumn('number', 'Transformers: Age of Extinction'); data.addRows(averageTimeInQueue); var options = { chart: { title: 'Box Office Earnings in First Two Weeks of Opening', subtitle: 'in millions of dollars (USD)' }, width: 600, height: 350, axes: { x: { 0: {side: 'top'} } } }; var chart = new google.charts.Line(document.getElementById('chart_div2')); chart.draw(data, options); } function averageTimeInQueue(){ var jsonData = $.ajax({ url: "/averageTimeInQueue", async: false, type: 'POST' }).responseText; return jsonData; } 

    1 answer 1

    Of course not an array, you send it as text. Serialize it in json

    on the res.send(JSON.stringify(data)); server res.send(JSON.stringify(data));

    on the data.addRows(averageTimeInQueue()) client data.addRows(averageTimeInQueue()) instead of data.addRows(averageTimeInQueue) and

     var jsonData = $.ajax({ url: "/averageTimeInQueue", dataType: "json", async: false, type: 'POST' }).responseText; return JSON.parse(jsonData); 
    • so anyway he writes that it is not an array - Andrei
    • @Andrei per client in the data.addRows (averageTimeInQueue) line, put brackets data.addRows (averageTimeInQueue ()) - ilyapt
    • also writes that it is not an array, somehow it is necessary to convert it into an array - Andrei
    • @Andrei is very strange, with a dataType: "json" it should be parsed. But fix the return jsonData to return JSON.parse (jsonData), it will work this way - ilyapt
    • thanks, that works) - Andrei