Calling a Javascript function from flask / python

13,068

See this link you can use ajax to load the table with out refreshing the page.

you can use flask jsonify to return json from your flask app. See this link and below example from flask doc

from flask import jsonify
@app.route('/_get_current_user')
def get_current_user():
    return jsonify(username=g.user.username,
                   email=g.user.email,
                   id=g.user.id)

will return the following json

{
    "username": "admin",
    "email": "admin@localhost",
    "id": 42
}
Share:
13,068
wese3112
Author by

wese3112

Updated on July 27, 2022

Comments

  • wese3112
    wese3112 almost 2 years

    I know Python very well, but I'm new to web-stuff and JavaScript. I found a post about Calling a python function from button on website (Flask).

    I want to do the following: I want to add a new row to an HTML table. The data will be coming from Python. I already found out that refreshing the site isn't a good way to do it, instead it seems JavaScript should be used. Say I have the following HTML code:

    <table class="table" id="myTable">
      <thead>
        <tr>
          <th colspan="2">This is a table</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>entry 1</td>
          <td>entry 2</td>
        </tr>
      </tbody>
    </table>
    <script src="js/scripts.js"></script>
    

    and in the scripts.js I have the following function (from the linked post):

    function appendRow(table_id) {
      var table_ref = document.getElementById(table_id).getElementsByTagName('tbody')[0];
      var new_row = table_ref.insertRow(table_ref.rows.length);
      var new_cell = new_row.insertCell(0);
      var new_text = document.createTextNode('New row');
      new_cell.appendChild(new_text);
    }
    

    Now disregarding the details how the function works / what can be optimized etc. my real question is: How can I call this function from Python / flask?

    Additionally: How can I pass data (say a JSON-structure) to the JavaScript function?

    Many thanks in advance!