Many web application require autocomplete. Here we going to create autocomplete which pulls records from mysql using devbridge autocomplete api.

Requirements:

1.Flask

2.MySQL

3.jQuery

This tutorial uses country names .To get country list

For Mysql:

https://github.com/bharathirasa/demo/blob/master/mysql-country-list-codes.sql

For Oracle:

https://github.com/bharathirasa/demo/blob/master/oracle-country-list.sql

 

HTML CODE:


<input type="text" name="country" id="autocomplete" class="form-control" placeholder="Enter Country name" />
 
Jquery Plugin to achieve Autocomplete from DevBridge
 
<script type="text/javascript" src="src/jquery.autocomplete.js"></script>

Download and include the devbridge api using 

https://www.devbridge.com/sourcery/components/jquery-autocomplete/

 

JQUERY CODE:


$("#autocomplete").autocomplete({
 
                              //lookup: countries,
 
                              serviceUrl:'autocomplete', //tell the script where to send requests
                              type:'POST',
                               width: 450, //set width
 
//callback just to show it's working
 
                              onSelect: function (suggestion) {
 
                              $('#selection').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
 
                              },
 
                              showNoSuggestionNotice: true,
 
                              noSuggestionNotice: 'Sorry, no matching results',
 
               });

Server(Flask) Script:


@app.route('/ajaxautocomplete',methods=['POST', 'GET'])
def ajaxautocomplete():
    result=''
    if request.method=='POST':
     query=request.form['query']
     
     try:
  
      with connection.cursor() as cursor:
        sql="select country_code data,country_name value from  countries where country_name like '%"+query+"%'"
        cursor.execute(sql)
        result = cursor.fetchall()
     finally:
      a=2
     return json.dumps({"suggestions":result})
    else:
     
     return "ooops"

 

Demo

Download

 

Output:

flask-ajax-mysql-autocomplete