I am trying to build Google Sankey Chart using data pulled from MySQL database.
After the page is loaded I am making ajax call to pull the data from MySQL and returning it to the view.
This is how I am returning data from PHP:
echo json_encode("['test', 'test2', 1],['test2', 'test3', 1],");
Now when I check in JavaScript the type of returned data it says "string".
console.log(typeof myData); // string
However the chart is expecting arrays. So when I am passing this data to function that builds chart it comes back with the error. Here is how I am trying to build it:
data.addRows([
myData
]);
But it comes back with:
Uncaught Error: Every row given must be either null or an array.
But if I hardcode that data directly in data.addRows it works perfectly fine... Like below works fine
data.addRows([
['test', 'test2', 1],['test2', 'test3', 1],
]);
How can I force JavaScript to accept myData returned from php?
I tried returning data from PHP as array and loop through it in JavaScript and populate the chart but sometimes I am returning 50000 rows or more and JavaScript does not handle looping through so many rows very well (slow and sometimes runs out of memory and crashes browser). So I thought if I return it as string JavaScript does not have to loop through it, just pass it to the chart builder.
EDIT: I am attaching my ajax call function and function that draws the chart
This is the ajax call that pulls data from php/mysql:
function ajaxCall() {
$(function() {
$.ajax({
type: "POST",
url: "/test",
dataType: "JSON",
success: function(myData) {
// Draw the graph
drawChart(myData);
},
error: function(xhr,status,error) {
console.log("error status: " + status + " / the error is: " + error);
},
});
});
}
This function will draw the chart using data returned from PHP:
function drawChart(myData) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'From');
data.addColumn('string', 'To');
data.addColumn('number', 'Weight');
data.addRows([
myData
]);
// Calculate graph height, by multiplying number of rows and fixed value
var rowsQty = data.getNumberOfRows();
var autoHeight = rowsQty*15;
if(autoHeight < 300) {
autoHeight = 300;
}
// Sets chart options.
var options = {
// width: 600,
height: autoHeight,
};
// Instantiates and draws our chart, passing in some options.
var chart = new google.visualization.Sankey(document.getElementById('sankey_basic'));
chart.draw(data, options);
}