-2

I want to get select value in HTML and use in python Flask. Because I could not find any way to get select tag option value via Flask, I get the value with JavaScript and then span it in a header. Now, I want to request the header but I could not. I get Key Error. Here is my HTML code.

        <label for="filtre_input">Neye göre karşılaştırmak istersiniz?</label>
        <select name="filtre_input" id="filt" onchange="filtreinputla();">
         <option selected="selected">Kategori</option>
         <option value="il">İl</option>
         <option value="tur">Tür</option>
         <option value="renk">Renk</option>
         <option value="duygu">Duygu</option>
       </select>

      <script type="text/javascript">
        function filtreinputla() {
        var filtreselect = document.getElementById("filt").value;
        console.log(filtreselect);
        document.getElementById("filtreselectid").innerHTML = filtreselect;
        }
      </script>
 <h3 id = "filtreselect_p" type = "hidden" name="filtreselect_p"><span id="filtreselectid"></span></h3>

Here is my app.py code.

@app.route("/nd", methods=['POST', 'GET'])
def func():
  flash("")
  filter = request.headers["filtreselect_p"]
  if filter == None:
      flash("Please, select something.")
      return render_template("index.html")
  else:
      result = my_function(filter)
      flash(result)
      return render_template("index.html")

I want to request the header or find a new approach to get select option tag value. Please, help if you can :)

davidism
  • 121,510
  • 29
  • 395
  • 339
user525252
  • 19
  • 1
  • Have you tried using the form tag? If you want you can check out some ways to pass data from frontend to backend on my answer here https://stackoverflow.com/questions/71879604/why-does-my-data-come-from-request-form-when-passing-it-to-the-backend-in-flask/71879986#71879986 – Winmari Manzano Apr 24 '22 at 07:23
  • Do you fundamentally understand this: https://stackoverflow.com/a/13840431/476? – deceze Apr 24 '22 at 07:30

1 Answers1

0

You should use form tag.
You can use GET or POST method.

<form method="get" action="/ng"><--or method="post"-->
<label for="filtre_input">Neye göre karşılaştırmak istersiniz?</label>
        <select name="filtre_input" id="filt" onchange="filtreinputla();">
         <option selected="selected">Kategori</option>
         <option value="il">İl</option>
         <option value="tur">Tür</option>
         <option value="renk">Renk</option>
         <option value="duygu">Duygu</option>
       </select>
</form>

If you use GET method your flask code is

request.args.get('filtre_input')

If you use POST method you can use

request.form.get('filtre_input')
user17517503
  • 155
  • 11