cmark
cmark

Reputation: 13

Passing MySQL data from flask to JavaScript for Google Charts

I've already checked out some similar questions here: How can I pass data from Flask to JavaScript in a template?

I'm trying to create a google chart using this example , where my data is coming from a database query, which is then parsed and formatted to be passed through Google's datasource python library, then converted into a json string. From there it is supposed to be passed through a JavaScript function in my HTML file in order to populate the Google Charts table. This last part seems to be causing me trouble. Here is the meat of my function in flask:

    description =  {"count": ("number", "Count"),"type": ("string", "Type")}

    data=[]
    rows = cur.fetchall()
    # formats MySQL data for JSON string 
    for row in rows:
        js = {'type': row[0], 'count': row[1]}
        data.append(js)

    # Loading it into gviz_api.DataTable (from Google Charts template)
    data_table = gviz_api.DataTable(description)
    data_table.LoadData(data)

     # Create a JSON string. (from google charts template)
    json= data_table.ToJSon(columns_order=("type", "count"), order_by="count")



render_template('myhtml.html' , json=json)

at the end of my function in flask, which is then passed through the following JavaScript function in my html file here:

<script>
 ... 
// taken from the Google Charts example
google.load('visualization', '1', {packages:['table']});
google.setOnLoadCallback(drawTable);
var json = '{{ json }}'

function drawTable(json) {
  var json_table = new google.visualization.Table(document.getElementById('table_div_json'));
  var json_data = new google.visualization.DataTable((json), 0.6);
  json_table.draw(json_data, {showRowNumber: true});
}

The chart is not drawn and I am left with only the header for the chart. I don't believe this is an issue with the format of my data or the HTML portion (which I've left out), for it is taken straight from the Google Charts template, so I've been trying to find problems in my JavaScript (which I am fairly new to). Can this string not be passed to the JavaScript function in this fashion? What alternative ways can it be done? Any pointers and suggestions would be great.

Upvotes: 1

Views: 1756

Answers (1)

reptilicus
reptilicus

Reputation: 10397

Probably have to escape it, something like:

{{json | safe}}

Upvotes: 1

Related Questions