1

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.

2
  • What does "doesn't seem to work" mean? What happens? Are there errors? Commented Jan 10, 2016 at 3:48
  • @dirn I just added some info regarding your question. Basically, the table is generated at /get_table but it is not appended to the div in the parent html. Commented Jan 10, 2016 at 4:23

1 Answer 1

3

The first thing I noticed is that you create ajax request, but in the get_table() method you are using render_template. Even it works, it is not going to process the jinja2 logic if you parse like this. If you like data back in the ajax call you will have to return plain string with already processed data like "...'<table>...<td>'+request.json['row1']+'</td>'..." and then bind it to the HTML. I would recommend using json instead of plain string, something like:

@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 jsonify(table_data)

And then bind the received data with jQuery to the table. Therefore you will also not need the jinja2 logic in the template, but plain html.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your suggestion. Indeed, your method works but I still would prefer to generate the table in an external html and make ajax append it to the parent html. It looks like it is not that simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.