
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Live Search Using Flask and jQuery
Introduction
The combination of Flask and jQuery gives a reliable solution for developing dynamic web apps. While jQuery is a quick, compact, and feature-rich JavaScript library, Flask is a well-known, lightweight web framework for Python. For the purpose of creating a live search feature in a Flask application, we will combine the strengths of these two technologies in this tutorial.
Prerequisites
Ensure that you have the following installed on your local computer before beginning the tutorial's main sections:
Python
Flask ? Install it via pip with pip install flask
jQuery ? Download it from the official website or use a CDN.
Setup
Make a new Flask application first. We'll begin with a straightforward programme that shows a webpage with a search box.
The file structure of the project is as follows ?
/flask_live_search /templates search.html app.py
In app.py ?
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('search.html') if __name__ == '__main__': app.run(debug=True)
Example
In search.html ?
<!DOCTYPE html> <html> <head> <title>Live Search with Flask and jQuery</title> </head> <body> <input type="text" id="search" placeholder="Search..."> </body> </html>
Live Search Using Flask And JQuery
Let's now include the live search feature.
Let's define some of the data to be searched through first. This information would normally originate from a database in a real application. However, we'll use a list of strings to keep things simple.
In app.py ?
data = ["Python", "JavaScript", "Java", "C++", "C#", "Swift", "Go", "Kotlin", "PHP", "Ruby"]
Our Flask application will then add a new route that will accept the search requests and provide the results.
from flask import request, jsonify @app.route('/search', methods=['GET']) def search(): query = request.args.get('query') results = [d for d in data if query.lower() in d.lower()] return jsonify(results)
A GET request with a query argument is accepted by the /search route. A list of all data items that match the query string is returned.
As soon as the user writes something into the search box, we'll edit our search.html to send a GET request to the /search route. We'll employ jQuery's $.get() function for this.
Example
<!DOCTYPE html> <html> <head> <title>Live Search with Flask and jQuery</title> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> </head> <body> <input type="text" id="search" placeholder="Search..."> <ul id="results"></ul> <script> $(document).ready(function(){ $('#search').on('input', function(){ var query = $(this).val(); $.get('/search', {query: query}, function(data){ $('#results').empty(); data.forEach(function(d){ $('#results').append('<li>' + d + '</li>'); }); }); }); }); </script> </body> </html>
As a basic demonstration of how a live search capability may be added to a Flask application using jQuery, our first example. We'll now delve more deeply into some of the important details.
The $.get() Function
As an abbreviated Ajax function, the $.get() function in jQuery is comparable to ?
$.ajax({ url: url, data: data, success: success, dataType: dataType });
Using an HTTP GET request, the $.get() function downloads data from the server. We employ a GET request in our Flask route for this reason.
The on('input') Event
Every time the value of a textarea or input element changes, the on('input') jQuery event is triggered. This is ideal for our use case because it can occur when the user types, deletes, or pastes text. As soon as the user writes something into the search box, it enables us to do a fresh search.
JSON Responses in Flask
To return our search results in JSON format, we're utilising the jsonify method in Flask. This is due to the fact that when you use the $.get() function, jQuery by default expects a JSON return. JSON (JavaScript Object Notation) is a simple data exchange format that is simple for both humans and machines to read, write, parse, and produce.
Example: Live Search with a Database
In a practical application, you would probably want to store and search your data in a database. Let's adapt our prior illustration to make use of SQLite, a compact disk-based database.
Install the flask_sqlalchemy library initially ?
pip install flask_sqlalchemy
Then make a fresh database and enter some information ?
from flask_sqlalchemy import SQLAlchemy app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class Item(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), nullable=False) @app.route('/') def home(): # Add some data if not Item.query.first(): items = ["Python", "JavaScript", "Java", "C++", "C#", "Swift", "Go", "Kotlin", "PHP", "Ruby"] for i in items: db.session.add(Item(name=i)) db.session.commit() return render_template('search.html')
To query the database, edit the /search route next ?
To query the database, edit the /search route next: @app.route('/search', methods=['GET']) def search(): query = request.args.get('query') results = Item.query.filter(Item.name.contains(query)).all() return jsonify([r.name for r in results])
This example shows how to connect to a SQLite database using Flask-SQLAlchemy. It is better suited for bigger datasets and allows up more advanced querying options like case-insensitive or partial matching.
Conclusion
As we've seen, live search is a powerful feature that may greatly enhance user experience on your website. It's also rather simple to integrate into a Flask application using jQuery. This article outlines the essential procedures needed to create a live search feature, although they can be enhanced to meet the unique requirements of every application.
It should be noted that the live search provided here searches for the query string anywhere in the data items and is case-insensitive. Additionally, this application conducts a new search with each keystroke, which could not be effective when dealing with enormous amounts of data. You could debounce the input to improve efficiency by holding off on the search for a predetermined period of time after the user has stopped typing.