article

Thursday, April 2, 2020

Python Flask Jquery Ajax Autocomplete


Python Flask Jquery Ajax Autocomplete

 
#app.py
from flask import Flask, Response, render_template, request
import json
from wtforms import TextField, Form

app = Flask(__name__)

class SearchForm(Form):
    autocomp = TextField('Insert City', id='city_autocomplete')


@app.route('/_autocomplete', methods=['GET'])
def autocomplete():
    cities = ["Olongapo City",
          "Angeles City",
          "Manila",
          "Makati",
          "Pasig",
          "Davao",
          "Cebu",
          "Quezon City",
          "Taguig"]
    print(cities)    
    return Response(json.dumps(cities), mimetype='application/json')


@app.route('/', methods=['GET', 'POST'])
def index():
    form = SearchForm(request.form)
    return render_template("search.html", form=form)

if __name__ == '__main__':
    app.run(debug=True)
//search.html
<head>
    <meta charset="utf-8">
 <title>Python Flask Jquery Ajax Autocomplete</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  </head>
<body>
{{ form.autocomp.label }}: {{ form.autocomp }}
<script>
    $(function() {
        $.ajax({
            url: '{{ url_for("autocomplete") }}'
            }).done(function (data){
                $('#city_autocomplete').autocomplete({
                    source: data,
                    minLength: 2
                });
            });
        });
</script>
  </body>
</html>

Related Post