I need to dynamically generate a table in my Flask app. I found in this post Rendering Jinja template in Flask following ajax response that it is possible to return html page via ajax. I decided to try to generate a table in an external html page and to append to the div in the parent html but I have a problem with that, more specifically how to append external html in ajax. Here is my simplified home.html:
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
<meta charset="UTF-8"/>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<button id="table">Get table</button>
<div id="my_table">
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</body>
</html>
table.html:
<table>
<thead>
<tr>
<th>#</th>
<th>Make</th>
<th>Model</th>
<th>Year</th>
</tr>
</thead>
<tbody>
{% for row in table_data %}
<tr>
{% for column in row %}
<td>{{ column }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
app.py:
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)
@app.route('/get_table', methods=["POST", "GET"])
def get_table():
row1 = request.json['row1']
row2 = request.json['row2']
table_data = [row_1, row_2]
return render_template('table.html', table_data=table_data)
if __name__ == "__main__":
app.run(debug=True)
main.js:
$('#table').on('click', function(){
$.ajax({
type: "POST",
url: "/get_table",
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({'row1': [1, 'honda', 'accord', 2004] ,
'row2': [2, 'toyota', 'camry', 2006]}),
dataType: 'json',
success: function(data){
$('#my_table').html(data);
},
error: function(error){
console.log(error);
},
});
});
$('#my_table').html(data) doesn't seem to work - the table is generated at /get_table but it is not appended to the #my_table div. Any comments/suggestions on how to make it work are highly appreciated.