Flask Dynamic data update without reload page
116,682
Working example:
app.py
from flask import Flask, render_template, request
import requests
from bs4 import BeautifulSoup
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/suggestions')
def suggestions():
text = request.args.get('jsdata')
suggestions_list = []
if text:
r = requests.get('http://suggestqueries.google.com/complete/search?output=toolbar&hl=ru&q={}&gl=in'.format(text))
soup = BeautifulSoup(r.content, 'lxml')
suggestions = soup.find_all('suggestion')
for suggestion in suggestions:
suggestions_list.append(suggestion.attrs['data'])
#print(suggestions_list)
return render_template('suggestions.html', suggestions=suggestions_list)
if __name__ == '__main__':
app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<title>Suggestions</title>
</head>
<body>
Search: <input type="text" id="search_form_input"></input>
<div id="place_for_suggestions"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$("#search_form_input").keyup(function(){
var text = $(this).val();
$.ajax({
url: "/suggestions",
type: "get",
data: {jsdata: text},
success: function(response) {
$("#place_for_suggestions").html(response);
},
error: function(xhr) {
//Do Something to handle error
}
});
});
</script>
</body>
</html>
suggestions.html
<label id="value_lable">
{% for suggestion in suggestions %}
{{ suggestion }}<br>
{% endfor %}
</label>
Related videos on Youtube
Author by
Konstantin Rusanov
Updated on July 09, 2022Comments
-
Konstantin Rusanov almost 2 years
i'm trying to create something like Google Suggest Tool (via suggest api http://suggestqueries.google.com/complete/search?output=toolbar&hl=ru&q=query )
I'm listening input changes, and send data go GET:
$("#search_form_input").keyup(function(){ var some_var = $(this).val(); $.ajax({ url: "", type: "get", //send it through get method data:{jsdata: some_var}, success: function(response) { }, error: function(xhr) { //Do Something to handle error } });
After that i'm handling this data and send it to Google API and got response in Python:
@app.route('/', methods=['GET', 'POST']) def start_page_data(): query_for_suggest = request.args.get('jsdata') if query_for_suggest == None: suggestions_list = ['',] pass else: suggestions_list = [] r = requests.get('http://suggestqueries.google.com/complete/search?output=toolbar&hl=ru&q={}&gl=in'.format(query_for_suggest), 'lxml') soup = BeautifulSoup(r.content) suggestions = soup.find_all('suggestion') for suggestion in suggestions: suggestions_list.append(suggestion.attrs['data']) print(suggestions_list) return render_template('start_page.html', suggestions_list=suggestions_list)
In Jinja trying to print it in HTML dynamically:
<label id="value_lable"> {% for suggestion in suggestions_list %} {{ suggestion }} {% endfor %} </label>
But variable in Jinja doesn't update dynamically and print empty list.
How to print suggestions from list dynamically in HTML?
-
furas over 7 yearsin JavaScript your
success:
function is empty so you do nothing with data from Flask. -
Konstantin Rusanov over 7 yearsWhat i need to fix?
-
furas over 7 yearsI think you don't know how AJAX/JavaScript work. JavaScript sends data to Flask, Flask sends back some data - better as JSON - and JavaScript receives this data and updates HTML in browser.
-
Konstantin Rusanov over 7 yearsCan you send few examples of, how a can handling this?
-
furas over 7 yearsI
success
function you have to find element in HTML - using$(...)
- and then you can update it - using data which you have inresponse
. -
furas over 7 yearsI would use in Flask separated function to send sugestions.
-
Konstantin Rusanov over 7 yearsUpdate inside tis success: function(response) {...} ? How i can receive data (list of suggestions) from python app?
-
furas over 7 years
success: function(response)
has sugestions in variableresponse
-
furas over 7 yearsif I try your google link directly in browser then it gives me empty page. I expect it returns data as JSON so your JavaScript could receive it directly - without Flask - and use to generate HTML on page.
-
Konstantin Rusanov over 7 yearsXML file, not JSON
-
furas over 7 yearsIt reaturns empty file - maybe it need Google Account and Google Project with private API key.
-
furas over 7 yearsOK, I had to use different text in query to get suggestions :)
-
Konstantin Rusanov over 7 yearsGet data from this file - not problem (on server side via flask), problem is - dynamically print suggestions in HTML (after entering each letter in input field)
-
furas over 7 yearsFlask should send only minimal HTML with sugestions and
sucess
should use ie.$("#place_for_sugestions").html(response)
-
-
Mike R over 6 yearsIs this considered safe? Someone could just navigate to https://.../suggestions and it would return a page. Is there some way that we can prevent returning the rendered template unless the call comes from the AJAX request?
-
furas over 4 yearsyou can check
if request.is_xhr:
to see if it was AJAX - but someone can use other tools (ie. Python modulerequests
) to send request with headerX-Requested-With: XMLHttpRequest
andis_xhr
will returnTrue
. You could check other headers - ie.User-Agent
- to recognize if it is browser but other tools can also send correct headerUser-Agent
. Question is if you really need so "safe" version.