Yet another question about flask and jquery autocomplete. I have been reading and trying the following answered questions without any success:
Flask AJAX Autocomplete
Using jQuery autocomplete with Flask
In particular the second answer is perfectly matching my case.
However for some reasons (maybe it's me not understanding what is supposed to do), the callback autocomplete(..)
is executed only once when I load the page (and correctly autocomplete the value in NAMES
) but never while typing in the textbox.
search.html
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script>
</head>
{{ form.autocomp.label }}: {{ form.autocomp }}
<script>
$(function() {
$.ajax({
url: '{{ url_for("autocomplete") }}'
}).done(function (data) {
$('#autocomplete').autocomplete({
source: data,
minLength: 2
});
});
});
</script>
application.py
from flask import Flask, Response, render_template, request
import json
app = Flask(__name__)
import wtforms as wt
from wtforms import TextField, Form
NAMES=["abc","abcd","abcde","abcdef"]
class SearchForm(Form):
autocomp= TextField('autocomp',id='autocomplete')
@app.route('/autocomplete',methods=['GET'])
def autocomplete():
search = request.args.get('term')
app.logger.debug(search)
return Response(json.dumps(NAMES), 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)
Try this
from flask import jsonify
NAMES=["abc","abcd","abcde","abcdef"]
@app.route('/autocomplete',methods=['GET'])
def autocomplete():
search = request.args.get('term')
app.logger.debug(search)
return jsonify(json_list=NAMES)
In Jquery:
<script>
$(function() {
$.ajax({
url: '{{ url_for("autocomplete") }}'
}).done(function (data) {
$('#autocomplete').autocomplete({
source: data.json_list,
minLength: 2
});
});
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With