Home > Software design >  Javascript / AJAX script to use autocomplete with an API
Javascript / AJAX script to use autocomplete with an API

Time:09-23

I want to have an autocomplete on my form and i'm using ajax for it.

with the code below, the get request is coming through, but it always gives 'no search result

edit - SOLUTION:

// inspiration from https://stackoverflow.com/questions/34704997/jquery-autocomplete-in-flask
      <script type="text/javascript">
                    $(function() {
                        $('#{{columnitem.name}}').autocomplete({
                            source:function(request, response) {
                                // Getting results from with getJSON API request
                                $.getJSON("{{'/autocomplete/'   keypair.table   '/'   columnitem.name}}",{ 
                                    q: request.term, // in flask, "q" will be the argument to look for using request.args
                                }, 
                                function(data) {
                                    response($.map(data, function(item) {
                                        return {
                                        label: item.{{columnitem.name}}, // The label(s) that will be shown in the autocompletelist
                                        value: item.{{columnitem.name}} // The value that will be selected
                                    };
                                    })); 
                                });
                            },
                            minLength: 2,
                            datatype: "json",
                            select: function(event, ui) {
                                console.log(ui.item.value); // When a value is selected, log it in the console
                            }
                        });
                    })
                    </script>

my Flask python code:


from cs50 import SQL
from flask import jsonify

# inspiration from https://stackoverflow.com/questions/34704997/jquery-autocomplete-in-flask
# Pro Grammer S: https://stackoverflow.com/users/19920475/pro-grammer-s
@app.route("/autocomplete/<tablename>/<columnname>", methods=['GET'])
def autocomplete_function(tablename, columnname):
    # Check whether the table is in the available tables first
    if tablename in formsdict:
        
        # If the tablename exists, get its column names
        columnames = ophalenkolomnamen(db, tablename)

        # Check whether the columnname requested is in the column names
        if columnname in columnames:

            # Get additional search arguments (to insert in the like format)
            q = str("%"   request.args.get('q')   "%")
            print(q)

            # get the requested autocomplete list

            # using CS50 to prevent SQL injection attacks
            string = f"SELECT * FROM `{tablename}` WHERE `{columnname}` LIKE ?;"
            autocompletelist = db.execute(string, q)
            
            return jsonify(autocompletelist)
    else:
        return []

Where {{columnitem.name}} and {{keypair.table}} are attributes of variables columnitem and keypair that are used in the flask render_template statement.

CodePudding user response:

The Solution that worked for me was the following code:

<script type="text/javascript">
                    $(function() {
                        $('#{{columnitem.name}}').autocomplete({
                            source:function(request, response) {
                                $.getJSON("{{'/autocomplete/'   keypair.table   '/'   columnitem.name}}",{
                                    q: request.term, // in flask, "q" will be the argument to look for using request.args
                                }, 
                                function(data) {
                                    response($.map(data, function(item) {
                                        return {
                                        label: item.{{columnitem.name}},
                                        value: item.{{columnitem.name}}
                                    };
                                    }));
                                });
                            },
                            minLength: 2,
                            datatype: "json",
                            select: function(event, ui) {
                                console.log(ui.item.value); // When selected log in the console.
                            }
                        });
                    })
                    </script>

Where {{columnitem.name}} and {{keypair.table}} are attributes of variables columnitem and keypair that are used in the flask render_template statement.

  • Related