tutorial101 is the one place for high quality web development, Web Design and software development tutorials and Resources programming. Learn cutting edge techniques in web development, design and software development, download source components and participate in the community.
#app.py
from flask import Flask,render_template,request,jsonify
from flask_mysqldb import MySQL
app = Flask(__name__)
mysql = MySQL(app)
#Enter here your database informations
app.config["MYSQL_HOST"] = "localhost"
app.config["MYSQL_USER"] = "root"
app.config["MYSQL_PASSWORD"] = ""
app.config["MYSQL_DB"] = "testingdb"
app.config["MYSQL_CURSORCLASS"] = "DictCursor"
@app.route("/")
def index():
return render_template("livesearch.html")
@app.route("/livesearch",methods=["POST","GET"])
def livesearch():
searchbox = request.form.get("text")
cursor = mysql.connection.cursor()
query = "select * from country where country LIKE '{}%' order by country".format(searchbox)
cursor.execute(query)
result = cursor.fetchall()
return jsonify(result)
if __name__ == "__main__":
app.run(debug=True)
templates/livesearch.html
//templates/livesearch.html
<!DOCTYPE html>
<html>
<head>
<title>Flask MySQL jquery ajax Live Search</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#livebox").on("input",function(e){
$("#datalist").empty();
$.ajax({
method:"post",
url:"/livesearch",
data:{text:$("#livebox").val()},
success:function(res){
var data = "<div class='list-group'>";
$.each(res,function(index,value){
data += "<p class='list-group-item list-group-item-action'>"+value.country+"</p>";
});
data += "</div>";
$("#datalist").html(data);
}
});
});
});
</script>
</head>
<body>
<div class="container">
<br/>
<p><h2>Flask MySQL jquery ajax Live Search</h2></p>
<input type="text" id="livebox" name="text" class="form-control" placeholder="Find country" autocomplete="off">
<p id = "datalist"></p>
</div>
</body>
</html>