[SOLVED] Calling/Invoking a Javascript function from python a flask function within html

Issue

I was creating a flask application and tried to call a python function in which I wanted to invoke some javascript function/code regarding the HTML template that I returned on the initial app.route('/')

If the user did something, then I called another function that should invoke or call a js function I have tried looking everywhere but I cannot make any sense of the solutions.

Here is the structure of my code:

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        #verify if the file is valid
        #here invoke js to do something (for example flash("test"))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''

Solution

You could execute a JavaScript function on load and have the function check for the condition. You can influence the outcome of this check by changing the condition with Python. If you use the render_template function of Flask, you do not have to write your HTML code within your Python file. For better readability I am using this functionality, but you can always put the HTML code into your Python code, as you have done before.

Your HTML template, e.g. named upload.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Upload new File</title>
</head>
<body onload="flashMessage()">
  <script>
    function flashMessage() {
      if ("{{ flash_message }}" == "True") {
        alert("[YOUR_MESSAGE_HERE]");
      }
    }
  </script>

  <h1>Upload new File</h1>
  <form method=post enctype=multipart/form-data>
    <input type=file name=file>
    <input type=submit value=Upload>
  </form>
</body>
</html>

Your Python code:

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        #verify if the file is valid
        #here invoke js to do something (for example flash("test"))
        return render_template('upload.html', flash_message="True")

    return render_template('upload.html', flash_message="False")

So, the condition line in your HTML file will render to

if ("True" == "True")

or

if ("False" == "True")

depending on if you want the flash message to show or not.

Answered By – Elisabeth Strunk

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.