skip to Main Content

I am trying to use value of dropdown from frontend to backend where on behalf of the dropdown value calculation will be happened and that endpoint will return a HTML page.
Would like to add that, I don’t need to get any response from the POST method (eg: return jsonify). So far, I am using Flask for backend and for frontend Vanilla JS.

I have successfully pass and fetched dropdown value using POST method in backend. I have also checked from server and browser console and no error found.

The approach I have taken do far:

Frontend

HTML file, written in index.html

<label for="mode">Select Mode:</label>
<select id="mode" name="mode">
    <option value="autoencoder">Autoencoder</option>
    <option value="decoder">Decoder</option>
</select>
<button id="Module_submitBtn">Chose Module</button>

<script src="static/js/call_module.js "></script>

JS file

function submitMode() {
    var selectedMode = document.getElementById("mode").value;

    fetch('/update_mode', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ mode: selectedMode })
    })
        .catch(error => console.error('Error:', error));
}

const submitBtn = document.getElementById('Module_submitBtn');
submitBtn.addEventListener('click', submitMode);

Backend

python file

# This is the desired endpiunt from where HTML file is rendered
@app.route("/decoder_graphical_view", methods=['GET'])
def decoder_graphical_view(name=None):
    config_val = Decoder_Config.config_val
    return render_template("decoder_graph.html",
                           N_value=config_val["Decoder_live_plot"]["N_"],
                           ebno_value=config_val["Decoder_live_plot"]["ebno_"],
                           phi_value=config_val["Decoder_live_plot"]["phi_"],
                           learningRate_value=config_val["Decoder_live_plot"]["learning_rate_"],
                           name=name
                           )

# This is the endpoint where POST method will work, dropdown value will come and it will call `decoder_graphical_view` function
@app.route('/update_mode', methods=['POST'])
def update_mode(name=None):
    selected_mode = request.json.get('mode')

    if selected_mode == 'autoencoder':

        return redirect(url_for('decoder_graphical_view'))


    elif selected_mode == 'decoder':
        return redirect(url_for('decoder_graphical_view'))

I have also tried the update_mode function in the following way but same result and failed.

@app.route('/update_mode', methods=['POST'])
def update_mode(name=None):
    selected_mode = request.json.get('mode')
    # set default value for the config data
    Decoder_Config.config_val["Decoder_live_plot"]["N_"]     = 100
    Decoder_Config.config_val["Decoder_live_plot"]["ebno_"]  = 2.0
    Decoder_Config.config_val["Decoder_live_plot"]["phi_"]   = 5
    Decoder_Config.config_val["Decoder_live_plot"]["train_"] = "True"
    train_var = str(Decoder_Config.config_val["Decoder_live_plot"]["train_"]).lower()
    if train_var == "true":
        train_var = True
    else:
        train_var = False
    Decoder_Config.config_val["Decoder_live_plot"]["learning_rate_"]   = 0.005

    if selected_mode == 'autoencoder':
        print("selected_mode: ", selected_mode)
        return render_template("decoder_graph.html",
                                N_value=config_val["Decoder_live_plot"]["N_"],
                                ebno_value=config_val["Decoder_live_plot"]["ebno_"],
                                phi_value=config_val["Decoder_live_plot"]["phi_"],
                                learningRate_value=config_val["Decoder_live_plot"]["learning_rate_"],
                                name=name
                                )

    elif selected_mode == 'decoder':
        return render_template("decoder_graph.html",
                                N_value=config_val["Decoder_live_plot"]["N_"],
                                ebno_value=config_val["Decoder_live_plot"]["ebno_"],
                                phi_value=config_val["Decoder_live_plot"]["phi_"],
                                learningRate_value=config_val["Decoder_live_plot"]["learning_rate_"],
                                name=name
                                )

Trial

So far what I have tried are listed below: 1, 2, 3, though could not get any valid result.

In server console I have seen the following message while I have pressed Submit button

"POST /update_mode HTTP/1.1" 302 -
"GET /decoder_graphical_view HTTP/1.1" 200

What could be the possible way to get a rendered HTML after calling the POST method?

2

Answers


  1. on behalf of the dropdown value calculation will be happened and that
    endpoint will return a HTML page

    This sounds like task for plain FORM, consider following example

    templates/index.html

    <html>
    <body>
    <form method="POST" action="/current">
    <label for="what">I want to know current</label>
    <select name="what" id="what">
    <option value="y">year</option>
    <option value="m">month</option>
    <option value="d">value</option>
    </select>
    <input type="submit">
    </form>
    </body>
    </html>
    

    templates/current.html

    <html>
    <body>
    {{answer}}
    </body>
    </html>
    

    application.py

    import datetime
    from flask import Flask, render_template, request
    app = Flask(__name__)
    @app.get("/")
    def hello():
        return render_template("index.html")
    @app.post("/current")
    def current():
        what = request.form["what"]
        today = datetime.date.today()
        if what=="y":
            answer = today.strftime("Year is %Y")
        elif what=="m":
            answer = today.strftime("Month is %m")
        elif what=="d":
            answer = today.strftime("Day is %d")
        else:
            answer = "Not supported"
        return render_template("current.html", answer=answer)
    if __name__ == "__main__":
        app.run()
    

    (tested in Flask 2.3.2)

    Login or Signup to reply.
  2. I guess the index.html is also within the Flask app templates, otherwise you’d have to provide the url, instead of just the /update_mode path, when calling fetch in your javascript module.

    To redirect from the response you’re getting from the backend, you just have to change window.location.href to the url passed in the redirect response model sent from the backend. Something like this:

    fetch('/update_mode', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ mode: selectedMode })
        })
            .then((response) => {
                if (response.redirected) {
                    window.location.href = response.url;
                }
            })
            .catch(error => console.error('Error:', error));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search