Passing html search box string which is not submitted yet to python flask

Viewed 191

I have a html search box. If users hit their keyboard, I would like to pass this variable which is not submitted yet to python flask. I have no idea how to handle this. First code is html search box part and second code is python flask code.

<br> <input name="Country" type="text" id="Country" placeholder="Enter Country" oninput="myFunction()"/> oninput:  <span id="result"></span>
    <script>
        function myFunction() {
//          result.innerHTML = Country.value;
            result.innerHTML = output;
        }; 
    </script>
@auth.route('/search', methods=['POST'])
def autoComplete():
    country = request.form[Country.value]
    output = autoCompletion.init(country)
    return render_template("search.html", output=output)

Is there any way that passing a html search box string which is not submitted yet to python flask? Any help would be appreciate.

1 Answers

This is a simple example using AJAX without ever submitting the form.

With every change within the form field, a request is sent to the server in the background. The data received are then added to the datalist assigned to the form field.

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/complete')
def complete():
    countries = ['China', 'India', 'USA']
    country = request.args.get('country', '')
    results = [x for x in countries if x.startswith(country)]
    return jsonify(results=results)
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form>
      <input type="text" name="country" list="countries" placeholder="Enter Country" />
      <datalist id="countries"></datalist>
    </form>

    <script type="text/javascript">
      (function() {
        let countryField = document.querySelector("input[name='country']");
        countryField.addEventListener('input', function(event) {
          fetch(`/complete?country=${encodeURIComponent(countryField.value)}`)
            .then(resp => resp.json())
            .then(data => {
              const dataList = document.getElementById("countries");
              dataList.innerHTML = "";
              
              const results = data.results;
              results.forEach(item => {
                let elem = document.createElement("option");
                elem.setAttribute("value", item);
                dataList.appendChild(elem);
              });

            })
            .catch(err => console.error("Error:", err));
        }, false);
      })();
    </script>
  </body>
</html>

The code could certainly be improved, but it illustrates the possibility of obtaining data dynamically without reloading the page or finally sending the form.
To make your work easier, I recommend using libraries like jQuery.

Related