Flask html template not executing JavaScript, or, the template is not rendering

48 Views Asked by At

I have my main route which returns index.html with no issues.

@app.route("/", methods=["GET", "POST"])
def index():
########################################
# block of logic code                  #
########################################
return render_template("index.html")

index.html has a button, when clicked, does a bunch of stuff and is then successfully routed to

@app.route("/edit", methods=["GET", "POST"])
def edit():
########################################
# block of logic code                  #
########################################
return render_template("successful_save_alert.html")

The block of code is successfully executed, however the issue lies on this last return render_template("successful_save_alert.html"). I have followed it with the debugger. It seems to be rendering (debugger enters the html), however the JavaScript inside successful_save_alert.html is not being executed.

Here is successful_save_alert.html

{% extends "index.html" %}
{% block script %}
<script>
    alert("Save successful!");
    console.log("alert");
</script>
{% endblock %}

Here is index.html

<!DOCTYPE html>

<html lang="en">
    <head>
        <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
        <link href="/static/styles.css" rel="stylesheet">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta charset="UTF-8">
        <title>Database</title>
    </head>
    <body>
        ########################################
        # block of HTML.                       #
        ########################################
        {% block script %}{% endblock %}
        <script src="static/edit.js"></script>
    </body>
</html>

The other thing I noticed is, in the Chrome inspect view, the successful_save_alert.html is not appearing in the Sources tab. Which is weird because the debugger seems to show it is rendering however it is not rendering in the browser.

My file structure is:

├── app.py
├── database.db
├── static
│   ├── edit.js
│   └── styles.css
└── templates
    ├── index.html
    └── successful_save_alert.html

Additionally, here are my flask configurations (which I have attempted to remove to see if this fixes the issue)

# Configure application
app = Flask(__name__)

# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True

@app.after_request
def after_request(response):
    """Ensure responses aren't cached"""
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"

Things I have tried:

  1. A debugger shows html is "rendering" (i.e. it successfully steps through successful_save_alert.html
  2. Sources tab in chrome does not show successful_save_alert.html
  3. File structure is correct
  4. Redirecting to a new route e.g. @app.route("/successful_save_alert.html, methods=["GET", "POST"]) and then rendering the html from here, but no luck...
  5. I even tried creating a separate JS in the static folder and triggering this from successful_save_alert.html however that did not work. Hence why I think the issue may lie in the html not being rendered and returned.
  6. Removed flask configurations

My ultimate goal: render successful_save_alert.html from the @app.route("/edit")... route and have the JS code be executed. To replicate full code, refer to GitHub

1

There are 1 best solutions below

0
Dr_Gurn On

Okay I worked it out. My understanding of fetch API is limited so I need to read up on why this was the case. But here is the resolution.

My button was redirecting to the "\edit" route with the fetch API. However, I did not handle fetch's returned Promise value.

What I needed to do was, if the fetch was successful, then redirect to another route with window.location.href = '/edit';

For the purposes of this button my final JS fetch code looks like

    // Send JSON dict to flask 
    const fetchPromise = fetch("/edit", {
        method: "POST",
        body: JSON.stringify(JSONDict)
    });

    fetchPromise
        .then((response) => {
            if (!response.ok) {
                throw new Error(`HTTP error: ${response.status}`);
            }
            else {
                alert("Save successful!")
                window.location.href = '/';
            }

        })