Displaying Chart With JSON Data From Flask Route

590 views
Skip to first unread message

Michael Syring

unread,
Apr 26, 2018, 11:09:14 AM4/26/18
to Google Visualization API
I'm trying to return a jsonified SQL query to javascript to display in google charts API.  I can get the chart to display data when its manually entered in the code, but when I try to pass my JSON data in by AJAX I get nothing...just a blank page.
I have the data formatted correctly, and returning via `json.dumps()`.  Here is a larger snippet of my code, I hope it helps.

Python route - this returns what I initially put:

@app.route("/charting", methods=["GET", "POST"])
@login_required
def charting():


    rows
= db.execute("SELECT * FROM history WHERE id = :id", id=session["user_id"])
    jsonData
= (json.dumps(rows))
   
return render_template("charting.html"), jsonData=jsonData


jsonified data check:
`[{'id': 1, 'weight': 180, 'calories': 2100, 'rewards': 1, 'date': '2018-04-12'}, {'id': 1, 'weight': 185, 'calories': 1800, 'rewards': -1, 'date': '2018-04-13'}, {'id': 1, 'weight': 180, 'calories': 1600, 'rewards': 1, 'date': '2018-04-14'},]`




My javascript references jsonData

              // get data
              $
.ajax({
                url
: '/charting',
                dataType
: 'json'
             
}).done(function ({{ jsonData }}) {
                loadData
(jsonData);
             
});

             
// load json data
             
function loadData(jsonData) {
                $
.each(jsonData, function(index, row) {
                  data
.addRow([
                    row
.date,
                    row
.weight,
                    row
.calories
                 
]);
               
});
                drawChart
();
             
}

             
// draw chart
              $
(window).resize(drawChart);
             
function drawChart() {
                chart
.draw(data, options);
             
}
           
});


I know the chart code works because I can manually enter data and it displays, but for some reason I'm not passing the variable correctly.  I've tried returning render_template and passing it into a jinja placeholder but that didn't work either.
Any help?  I'm sure it's something to do with the way I have the data loading, but I am new to JavaScript (and not comfortable with it).
Reply all
Reply to author
Forward
0 new messages