Without reloading , dynamically update data in flask using ajax - javascript

I'm trying to update data in flask without reloading. Using ajax and javascript , I got the updated value in python , but it didn't make changes to html template which is rendered. Note that I also used Modular Apllications with Blue Print but I feel that is not the reason. Not to confuse with too much codes , I briefly changed and uploaded simple version. Please explain and point out my mistake or error why I'm not getting my expectation.
In app.py
from flask import render_template, request, Flask
app = Flask(__name__)
#app.route("/")
def home():
if request.args.get("field_changes"):
inps = request.args.get("field_changes")
else:
inps = 2
print(inps)
return render_template("home.html",num = inps)
if __name__ == "__main__":
app.run()
In home.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<input type="number" name="dynamic_inps" max="10" min="2" id="add_inps">
<h3>Your update value is : {{ num }}</h3>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.3.min.js">
inps = document.getElementById("add_inps")
$(document).on("input",'#add_inps',function(){
fields = $("#add_inps").val()
$.ajax({
type:"get",
url:"/calculations",
data : {field_changes:fields},
})
})
</script>
</body>
</html>
Although the value is changed in python script , it is not changed in html " Your update value is : ".

Related

My issues with JavaScript using $.(get) request in Flask App

Hello: I'm a newbie in programming so this problem may turn out to be trivial.
I have programmed a dice game (called 10,000) to teach myself python. I now want to make a simple web app re-using some of that python code. I'm using a Flask framework (+ Pythonanywhere as my web dev). I was able to put a simple CSS grid together with a CSS stylesheet and inserted a couple of JS buttons and a few HTML objects. I added a Jquery GET request to the button to get some values from the python code. So far, so good.
When I click the button though, the grid is duplicated (i.e. everything on the page appears twice); and, weirdly, only one of the buttons seems to work and returns the random values.
Now I'm not sure what I'm doing wrong. I don't see any errors popping up in the developer tool and I see the random numbers appear on the screen. Could you help me find where I messed up?
my flask app:
import random
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/')
def hello():
data = random.randint(1,6)
if request.method == "GET":
return render_template('main.html',data=data)
if __name__ == '__main__':
app.run()
HTML template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to- fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" linkhref="/static/css/styles.css">
</head>
<body>
<div class="grid">
<div class="title">
<h1>10,000</h1>
</div>
<div class="dice">
<div class="card" id="card1">
<p>{{ data }}</p>
</div>
</div>
<div class="roll">
<div class="round-button" id="roll-button">
<div class="round-button-circle">
<a class="round-button">Save</a>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function() {
$('#roll-button').click(function() {
$.get('/', function(data){
var data = data;
document.getElementById("card1").innerHTML = data;
});
});
});
</script>
in the app you need add check for ajax, and return json:
from flask import Flask, render_template, request, jsonify
# add jsonfy to ipmport ^^^^^^^
def hello():
data = random.randint(1, 6)
# add next two line
if request.is_xhr:
return jsonify(data=data)
if request.method == "GET":
return render_template('main.html', data=data)
in the html use data.data
document.getElementById("card1").innerHTML = data.data
<!-- ^^^^^^ -->

How to add a loading gif to the page when a function runs in the background in Flask?

I have written a Flask app that displays a page with a button, when the user clicks on that button a Python function is called which does some processing (which usually takes about 2 minutes). After this processing is over, a new page opens displaying the results. Now I want to include a 'loading gif' that indicates the user that the processing is in progress. How do I do this? Here is an example of what my code looks like.
app.py
from flask import Flask, render_template
import time
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/result', methods=['POST'])
def result():
time.sleep(5) # indicates the time delay caused due to processing
return render_template('result.html')
if __name__ == '__main__':
app.run(debug=True)
index.html
<html>
<body>
<form method=post action="/result">
<input type=submit value='Start Processing' name='submit_btn'>
</form>
</body>
</html>
result.html
<html>
<body>
<h1> Processing Done </h1>
</body>
</html>
This needs to be done on the client side only.
Add jquery in your header section:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
Add this to your submit button code:
onclick="$('#loading').show();"
Get a loading.gif image Add below code after your form in html
<div id="loading" style="display:none;"><img src="loading.gif" alt="" />Loading!</div>
References:
1 2
The above code works, but you may consider using: onsubmit="$('#loading').show();" inside of the form element in the place of:
onclick="$('#loading').show();"
This will ensure that the loading animation is only displayed once your form is successfully submitted. Something like a required field could prevent the submission from going through, but with the listener being "on click", you will still display the loading gif, which may confuse your users.

Trying to invoke python function from js using jQuery and Flask

I'm trying to design an interactive website for a presentation I'm making. I'm new at all this flask stuff, and I'm having some hard time understanding why my code doesnt work.
I'm trying to create a website, that every line in it is clickable, and on click I want to bind a python function that according to the text of the line do some calculation and replaces that text.
For that I have build a simple html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>click demo</title>
</head>
<body>
<p>2016-04-21 09:12:59</p>
<p>Second Paragraph</p>
<p>2016-04-21 09:12:59 bla bla</p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$( "p" ).click(function() {
$.getJSON('/background_process', {
line: $(this).text(),
}, function(data) {
$(this).text(data.result);
});
return false;
});
</script>
</body>
</html>
I also wrote flask code that should be binded once I click some line on my web page:
from flask import Flask, jsonify
app = Flask(__name__)
from flask import render_template
import re
#app.route("/")
def index():
return render_template('index.html')
#app.route("/background_process")
def background_process():
try:
lang = request.args.get('line', 0, type=str)
string = lang.split()[0]
if re.match(r'\d\d\d\d-\d\d-\d\d',string):
return jsonify(result=string)
else:
return jsonify(result="Doesnt start with a date")
except Exception as e:
return str(e)
if __name__ == "__main__":
app.run()
The problem is that the function does not work for some reason unless i'm specifying which spot to put the text by id of a slot in my html page, and I cant understand what went wrong.
You have two problems in your app.
The first one is that you are not importing the request module:
from flask import Flask, jsonify, request
Second, in your template, you are referring to this that is out of scope.
This should work:
$( "p" ).click(function() {
var this_p = this;
$.getJSON('/background_process', {
line: $(this_p).text(),
}, function(data) {
$(this_p).text(data.result);
});
return false;
});

d3 pie chart with flask server

I'm using the built-in flask server and I want to show an animated pie chart, like here:
http://codepen.io/tpalmer/pen/jqlFG
or
http://jsfiddle.net/thmain/xL48ru9k/1/
For simplicity, I use the latter one.
The python flask server code is:
from flask import Flask, render_template, request, flash
from forms import ContactForm
app = Flask(__name__)
app.secret_key = 'blah'
#app.route('/', methods = ['GET', 'POST'])
def test():
return render_template('test.html')
if __name__ == '__main__':
app.run(debug = True)
I did copy the javascript code provided on the webpage to the file static/script2.js
and the css code to static/css/style_d3.css
My HTML code is
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="//style_d3.css" type="text/css">
</head>
<body>
<p>test</p>
<div class="animated-ring">
<svg></svg>
</div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="//script2.js"></script>
</body>
</html>
I run the webpage through the flask server. But I get a webpage that just says "test", there's no chart.
What do I do wrong?
I'd really appreciate if someone could help me.
You only render the test.html at "/" path, the script2.js needs to be rendered too at "/script2.js".
Try this one liner at your project's root directory to host all files:
python -m SimpleHTTPServer
I think you need to set to a path your js file. In your app dir create a static folder then put your script2.js file and when you call this file at html use flask url_for() function
src="{{url_for('static', filename='script2.js'}}"

Separating html and JavaScript in Flask [duplicate]

This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 6 years ago.
Hey I've got the following problem:
I am building a little flask app, and usually i just stick with bootstrap and jinja templates to get what I want, but this time I needed a bit more customised version. In order to get a grip I started with a simple example of using custom js and flask to get the basic right. But lets go into detail:
Assume I have a simple flask web app called app.py located in my_app/ which looks like this
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(port=8080, debug=True)
and the corresponding index.html, which is located in my_app/templates, is simply
<!DOCTYPE html>
<html>
<body>
<p>Clicking here will make me dissapear</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$("p").click(function(event){
$(this).hide();
});
});
</script>
</body>
</html>
then I see the expected result, that is, i can click on the paragraph to make it disappear.
BUT: I would like to put the javascript part into a main.js file under static/js/. like so:
$(document).ready(function() {
$("p").click(function(event){
$(this).hide();
});
});
and the index.html becomes:
<!DOCTYPE html>
<html>
<body>
<p>Clicking here will make me dissapear</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src='/js/main.js'></script>
</body>
</html>
Unfortunately nothing will happen. I have tried other ways of referencing the script file as well but until now nothing works. I have the impression im missing something really simple. Thanks in advance!
Simply invoke the url_for function within the template, referencing the special static endpoint so that the correct url to the desired target resource be created. As the desired target is the main.js file inside static/js, this would lead to the following:
<script type=text/javascript src="{{
url_for('static', filename='js/main.js')
}}"></script>
The rest of the quickstart guide contains additional useful information.

Categories