1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #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 ) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | //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> $(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> |