article

Saturday, January 23, 2021

Python Flask Autosuggest using jQuery Ajax and Mysql database

Python Flask Autosuggest using jQuery Ajax and Mysql database

app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
 
app = Flask(__name__)
        
app.secret_key = "caircocoders-ednalan"
        
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'testingdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
        
@app.route('/')
def index():
    return render_template('index.html')

@app.route("/ajaxpost",methods=["POST","GET"])
def ajaxpost():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)    
    if request.method == 'POST':
        queryString = request.form['queryString']
        print(queryString)
        query = "SELECT * from countries WHERE value LIKE '{}%' LIMIT 10".format(queryString)
        cur.execute(query)
        countries = cur.fetchall()
    return jsonify({'htmlresponse': render_template('response.html', countries=countries)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Python Flask Autosuggest using jQuery Ajax and Mysql database</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
function suggest(inputString){
    if(inputString.length == 0) {
        $('#suggestions').fadeOut();
    } else {
        $('#country').addClass('load');
        $.post("/ajaxpost", {queryString: ""+inputString+""}, function(data){
                $('#suggestions').fadeIn();
                $('#suggestionsList').html(data); 
                $('#suggestionsList').append(data.htmlresponse);
                $('#country').removeClass('load');
        });
  }
}
function fill(thisValue) {
  $('#country').val(thisValue);
  setTimeout("$('#suggestions').fadeOut();", 600);
}
</script>
<style>
#country {
 width:200px;
 padding:3px;
 font-size:110%;
 vertical-align:middle;
}
.suggestionsBox {
 width: 200px;
 color: #fff;
 margin:0;
 padding:0;
 background:#86BAC7;
 top:0;
 left:0;
}
.suggestionList {
 margin: 0px;
 padding: 0px;
}
.suggestionList ul li {
 list-style:none;
 margin: 0px;
 padding: 6px;
 border-bottom:1px dotted #98BE56;
 cursor: pointer;
}
.suggestionList ul li:hover {
 background-color: #006E89;
 color:#000;text-align: left;
}
ul {
 font-family:Arial, Helvetica, sans-serif;
 font-size:11px;
 color:#FFF;
 padding:0;
 margin:0;
}
.load{
background-image:url(img/loader.gif);
background-position:right;
background-repeat:no-repeat;
}
#suggest {
 position:relative;
}
.sf_active{
 border:2px #8BB544 solid;
 background:#fff;
 color:#333;
}
</style>
</head>
<body> 
<div style="padding-left: 100px;">  
<p><h1>Python Flask Autosuggest using jQuery Ajax and Mysql database</h1></p>
<form id="form" action="#">
  <div id="suggest"><p><b>Start to type a country:</b></p>
   <input type="text" size="25" value="" id="country" onkeyup="suggest(this.value);" onblur="fill();" class="sf_active" />
   <div class="suggestionsBox" id="suggestions">
     <div class="suggestionList" id="suggestionsList">   </div>
  </div>
  </div>
</div>  
</form>
</body>
</html>
templates/response.html
//templates/response.html
<ul>
      {% for row in countries %} 
      <li onClick="fill('{{row.value}}')">{{row.value}}</li>
      {% endfor %}
</ul>

Related Post