Using jQuery autocomplete with Flask

This question has been asked before, and I think I did what I saw, but I don’t know what I am doing wrong. I don't know much about jQuery, but I will do my best to explain what I'm trying to do.

I want to autofill based on a query from a database, so I have this in my template:

<script type="text/javascript"> $(function() { $( "#function_name" ).autocomplete({ source: '{{url_for("autocomplete")}}', minLength: 2, }); }); </script> <form id="function_search_form" method="post" action=""> {{form.function_name}} </form> 

The form is generated by this Flask form class:

 class SearchForm(Form): function_name = TextField('function_name', validators = [Required()]) 

And here is the autocomplete function:

 @app.route('/autocomplete') def autocomplete(): results = [] search = request.args.get('term') results.append(db.session.query(Table.Name).filter(Table.Name.like('%' + search + '%')).all()) return dumps(results) 

So jQuery should go to the autocomplete function and return the JSON back to autocomplete. At least I think what is happening. What am I doing wrong here?

+3
jquery python flask autocomplete
source share
2 answers

Update:

autocomplete does not process the Ajax request automatically, if you give it a url, you have to do it manually:

 $(document).ready(function() { $.ajax({ url: '{{ url_for("autocomplete") }}' }).done(function (data) { $('#function_name').autocomplete({ source: data, minLength: 2 }); }); } 

You may need to change the way you handle the returned data, depending on what your API returns.

Update 2:

The result of your server-side request is as follows:

 [[["string1"], ["string2"], ... ["stringn"]]] 

You can smooth it before sending:

 import itertools flattened = list(itertools.chain.from_iterable(result[0])) 

But you can probably improve your query to return a list of strings directly. You will need to post all the code if you need help.

+3
source share

In fact, you don’t even need a request for this job! Using the standard jQuery-ui autocomplete, you can throw your possible elements into a jinja variable, and then:

 <script type="text/javascript"> $('#search_form').autocomplete({ source: JSON.parse('{{jinja_list_of_strings | tojson | safe}}'), minLength: 2, delay: 10, }); </script> 

This is very convenient if the elements are attached to current_user , as in Flask-Login .

 <script type="text/javascript"> $('#search_form').autocomplete({ source: JSON.parse('{{current_user.friends | map(attribute="name") | list | tojson | safe}}'), minLength: 2, delay: 10, }); </script> 
+1
source share

All Articles