Ramesh m
Ramesh m

Reputation: 15

flask variable access from HTML

app.py

@app.route('/cma/connect', methods=['GET', 'POST'])
def connect_management():
    user = request.form.get('all_classes')
    print('user:', user)
    return str(user)
@app.route('/')
def index():
   return render_template('app.html',
                           all_classes=default_classes)

app.html

<select name="selected_cma" class="form-control" id="all_classes">

                      {% for o in all_classes %}
                      <option  value="{{ o }}" selected>{{ o }}</option>
                      {% endfor %}   
                  </select> 
                </div>
                <div class="form-group col-xs-3">
                  <label for="all_entries">the manager</label>

                    <button class="form-control" id="button" onclick="connect()">the reciever</button>
                    <p id="countdown"></p>

js code inside the app.html

 $('#button').click( function(event) {
                event.preventDefault();

                $.post("/cma/connect", $('#form').serialize(), function(data) {
                    //alert(data);
                    countdown = $("#countdown");
                    countdown.append(data + "<br/>");
                });
            });

my result

user: None
127.0.0.1 - - [19/Jun/2020 10:03:11] "POST /cma/connect HTTP/1.1" 200 -

what i want

user: (the selected option from the dropdown menu)

to conclude the problem

i want to get the selected option back to my flask api for further usage and display it without going to a new tab

are there any new ways?

Upvotes: 0

Views: 379

Answers (1)

furas
furas

Reputation: 143097

If you don't want to use <form> in code (which is very strange) then you can try

<script>
    $('#button').click( function(event) {
        event.preventDefault();

        var selected = $("#all_classes :selected").val();

        alert("selected: " + selected);

        $.post("/ra/connect", {"selected_cma": selected}, function(data) {
            //alert(data);
            countdown = $("#countdown");
            countdown.append(data + "<br/>");
        });
    });
</script>

Rest should be the same.

JavaScript sends {"selected_cma": selected} so Flask has to use the same name in form.get('selected_cma')

@app.route('/cma/connect', methods=['GET', 'POST'])
def connect_management():
    user = request.form.get('selected_cma')
    print('user:', user)
    return str(user)

and

<select name="selected_cma" class="form-control" id="all_classes">
    {% for o in all_classes %}
     <option  value="{{ o }}" selected>{{ o }}</option>
    {% endfor %}   
</select> 
</div>

<div class="form-group col-xs-3">
     <label for="all_entries">the manager</label>
     <button class="form-control" id="button">the reciever</button>
     <p id="countdown"></p>

And don't need onclick="onclick()" because $('#button').click(...) already assign function. And if you have some function onclick() then it can makes some other problems.


EDIT:

Minimal working code

from flask import Flask, request, render_template_string

app = Flask(__name__)

@app.route('/')
def index():
    return render_template_string('''<html>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

   <select name="selected_class" class="form-control" id="all_classes">
   {% for o in all_classes %}
      <option  value="{{ o }}" selected>{{ o }}</option>
   {% endfor %}   
   </select> 
   <button class="form-control" id="button">Get gateways</button>

<p id="countdown"></p>

<script>
    $('#button').click( function(event) {
        event.preventDefault();

        var selected = $("#all_classes :selected").val();

        alert("selected: " + selected);

        $.post("/ra/connect", {"selected_cma": selected}, function(data) {
            //alert(data);
            countdown = $("#countdown");
            countdown.append(data + "<br/>");
        });
    });
</script>
</html>''', all_classes=['Hello', 'World'])

@app.route('/ra/connect', methods=['GET', 'POST'])
def connect_management():
    print(request.form)
    print(request.data)
    user = request.form.get('selected_cma')
    print('user:', user)
    return str(user)

app.run()

BTW: previous question: how to access the selected dropdown back to flask

Upvotes: 1

Related Questions