I am trying to populate a javascript array that will be used to pass into the Google Visualizations API
I have multiple tables containing simple stock data, and each element of the array will hold some piece of information from one table. So far, this is how I populate the array
function drawMapOfPortfolio(symbols, chart_div) {
var gdata = new google.visualization.DataTable();
gdata.addColumn('string', 'Symbol');
gdata.addColumn('string', 'Sector');
gdata.addColumn('number', 'Volume');
gdata.addColumn('number', 'Percent Change');
gdata.addRow(["Portfolio", null, 0, 0]);
gdata.addRow(["Information Technology", "Portfolio", 0, 0]);
gdata.addRow(["Financials", "Portfolio", 0, 0]);
gdata.addRow(["Consumer Staples", "Portfolio", 0, 0]);
gdata.addRow(["Consumer Discretionary", "Portfolio", 0, 0]);
//setup arrays to store the XHR objects to resolve
//and to store the data returned from the server for each request
var jqXHRs = [],
data = [];
//your loop will run faster if you cache the length of the array
for(i=0, len = symbols.length; i < len; i++) {
//create an IIFE to save the state of the `i` variable for each callback function
//IIFE = Immediately-Invoked-Function-Expression
(function (i) {
var symbol = symbols[i];
jqXHRs[i] = $.ajax({
url: "mysql_api.php",
type: "GET",
data: { sqlquery: "SELECT volume, day_change_percent, sector FROM " + symbol + " LEFT JOIN sector USING(symbol) ORDER BY unixTS DESC LIMIT 1" },
dataType: "json",
success: function(serverResponse) {
var treemapData = [symbol, serverResponse[0]["sector"], parseFloat(serverResponse[0]["volume"]), parseFloat(serverResponse[0]["day_change_percent"])];
data[i] = treemapData;
}
});
})(i);
}
//when all the XHR objects resolve, add their server responses to your `gdata` object
$.when(jqXHRs).then(function () {
gdata.addRows(data);
alert(data);
var chart = new google.visualization.TreeMap(document.getElementById(chart_div));
chart.draw(gdata, {
minColor: '#f00',
midColor: '#ddd',
maxColor: '#0d0',
headerHeight: 15,
fontColor: 'black',
showScale: true
});
});
}
but in order to do so, I have to set async to false. By setting async to true, the queries are sent out and google visualizations tries to draw the chart before the array is populated. Are there any ways around this? I think what I am looking for is
Use async $.ajax call to populate the array, but then wait for everything to sync before calling Google Visualization’s draw function.
Updated: changed javascript code but “data” array is empty inside $.when
A Stern Word of Warning
You are passing full SQL queries into your server-side script. This is extremely unsecure as I can just use my developer console to paste in any SQL I want to run. For instance I could delete your whole database very easily…