Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask + jquery autocomplete

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)
like image 321
memecs Avatar asked Mar 17 '14 08:03

memecs


1 Answers

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>
like image 94
kartheek Avatar answered Oct 14 '22 10:10

kartheek