Ajax after form submit - python

How do you do an ajax post after a successful submit form post. I want to take the input submitted on the form, do some calculations based on that input, and display the results on the front-end without the page refreshing.
FLASK
#app.route('/', methods=['GET', 'POST'])
def app_home():
if request.method == 'POST':
input_amount = request.form['input_amount']
input_amount = float(input_amount)
amount1 = input_amount * 12
amount2 = input_amount * 10
return render_template("index.html", amount1=amount1,amount2=amount2,)
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
index.html
<form method="post">
<div class="mb-3">
<label>Enter amount</label>
<input name = "input_amount" type="text" class="form-control" placeholder="amount">
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
<div class="container">
<p id = "response">result is: ${{amount1}}</p>
<p id = "response">result is: ${{amount2}}</p>
</div>
AJAX request
<script>
$(document).ready(function () {
$('form').on('submit', function (event) {
$.ajax({
data: { input_amount : input_amount},
type: 'POST',
url: '/'
})
.done(function (data) {
$('#response').text(data.output).show();
});
event.preventDefault();
});
});
</script>

As per the documentation the correct way is not using a form. Truth be told you don't want to submit a form right? You just want to pass the input values.
So I tried out the documentation code (since i'm also studing this "ajax + flask connection" for my app) and this should answer your question. Made a button class since you (and I) prefer button to a link.
app.py
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
#app.route('/_add_numbers')
def add_numbers():
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug = True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$SCRIPT_ROOT = {{ request.script_root|tojson }};
</script>
<title>Document</title>
<style>
.button {
background-color: #5b4caf;
border: none;
color: white;
padding: 0.75rem 0.75rem;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 14px;
border-radius: 3px;
}
</style>
</head>
<body>
<h1>jQuery Example</h1>
<p>
<input type="text" size="5" name="a" /> +
<input type="text" size="5" name="b" /> = <span id="result">?</span>
</p>
<p>
Calculate server side
<script>
$(function () {
$("a#calculate").bind("click", function () {
$.getJSON(
$SCRIPT_ROOT + "/_add_numbers",
{
a: $('input[name="a"]').val(),
b: $('input[name="b"]').val(),
},
function (data) {
$("#result").text(data.result);
}
);
return false;
});
});
</script>
</p>
</body>
</html>

Related

MongoDB Database Malfunction

I'm building a project and I'm using MongoDB and Node.js. I converted a csv file to a dict using the df.to_dict(orinet = tight). When I print from the database it prints out the same thing multiple times and doesn't even access the other data and I have no idea what the problem is when printing from index.ejs
files = ["Brandeis_ClipperShipGrant_2023 .xlsx" , "Google_ClipperShipGrant_2023 .xlsx"]
for file in files:
filepath = file
data_xls = pd.read_excel(filepath, index_col=None)
data_xls.to_csv('csvfile.csv')
client = pymongo.MongoClient(".......")
df = pd.read_csv("csvfile.csv")
data = df.to_dict(orient = "tight")
db = client["ClipperShipGrantData"]
db.ClipperShipGrantData.insert_one(data)
index.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ClipperShip</title>
<link rel="stylesheet" type="text/css" href="/css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<header>
<div class="container">
<div class="logo">
<img src="/html/Images/logo.png" alt="ClipperShip">
</div>
<div class="main-title">
<h1>Clipper Ship Foundation</h1>
</div>
<div class="nav">
<ul>
<li>Go To Main Page</li>
<li>About</li>
<!-- print all arrays in data array in console -->
<% for(var i = 0; i < moviesList["data"].length; i++) { %>
<p>
<%= moviesList["data"] %>
</p>
<% } %>
<%= moviesList["data"] %>
<%= console.log(moviesList["data"]) %>
</ul>
</div>
</div>
</header>
<section>
<div id="drop-zone">
<p>Drop files here</p>
<input type="file" id="file-input" multiple>
<p id="error-message"></p>
<ul id="file-list"></ul>
</div>
</section>
<footer>
</footer>
<!-- <script src="/frontend/javascript/dynamic.js"></script> -->
<script src="/javascript/dynamic.js"></script>
</body>
</html>
server.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const ejs = require('ejs');
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/frontend'));
mongoose.connect(".....")
const db = mongoose.connection;
const collection = db.collection('ClipperShipGrantData');
console.log(collection);
const moviesSchema = new mongoose.Schema({
index: Array,
columns: Array,
data: Array,
index_names: Array,
column_names: Array
});
const Movie = mongoose.model("Movie", moviesSchema);
app.get('/', (req, res) => {
collection.findOne({}, function(err, doc) {
if (err) throw err;
res.render('index', {
moviesList: doc
})
});
})
app.get('/data', (req, res) => {
collection.findOne({}, function(err, doc) {
if (err) throw err;
res.render('data', {
moviesList: doc
})
});
})
app.listen(4000, function() {
console.log('Server is running on port 4000');
})

how to use ajax and flask return value?

How can I put the first value of the list in function make progress(i)? list is the value returned from flask!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Changing the Value of Bootstrap 4 Progress Bar Dynamically</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js"></script>
<style>
.bs-example{
margin: 20px;
}
</style>
</head>
<body>
<div class="bs-example">
<!-- Progress bar HTML -->
<div class="progress">
{{rist}}
<div class="progress-bar progress-bar-striped" style="min-width: 20px;"></div>
</div>
<form action="/list" method="POST">
<input type="hidden" name="ID" value="">
<input type="hidden" name="path" value="{{path}}">
</form>
<!-- jQuery Script -->
<script>
var i = rist;
function makeProgress(){
if(i < 100){
i = i + 1;
$(".progress-bar").css("width", i + "%").text(i + " %");
setTimeout("makeProgress()", 100);
}
// Wait for sometime before running this script again
else { document.forms[0].submit(); }
$.ajax({
type:'post',
async:'true',
url:'http://127.0.0.1:5000/ ',
data:{rist},
dataType: 'json',
success: function(data){rist
}
});
};
</script>
</div>
</body>
</html>
this is print(rist) // .py
list = [(h, e, dictionary[e]) for h, e in zip(category_name, category_id)]
x = []
for j in list:
x.append(j)
rist = str(100*(len(x) / len(list)))
print(rist)
1.1235955056179776
2.247191011235955
3.3707865168539324
4.49438202247191
5.617977528089887
6.741573033707865
7.865168539325842
8.98876404494382
10.112359550561797
11.235955056179774
12.359550561797752
13.48314606741573
14.606741573033707
15.730337078651685
16.853932584269664
17.97752808988764
19.101123595505616
20.224719101123593
21.34831460674157
22.47191011235955
23.595505617977526
24.719101123595504
25.842696629213485
26.96629213483146
28.08988764044944
29.213483146067414
30.337078651685395
31.46067415730337
32.58426966292135
33.70786516853933
34.831460674157306
35.95505617977528
37.07865168539326
38.20224719101123
39.325842696629216
40.44943820224719
41.57303370786517
42.69662921348314
43.82022471910113
44.9438202247191
46.06741573033708
47.19101123595505
48.31460674157304
49.43820224719101
50.56179775280899
51.68539325842697
52.80898876404494
53.93258426966292
55.0561797752809
56.17977528089888
57.30337078651685
58.42696629213483
59.55056179775281
60.67415730337079
61.79775280898876
62.92134831460674
64.04494382022472
65.1685393258427
66.29213483146067
67.41573033707866
68.53932584269663
69.66292134831461
70.78651685393258
71.91011235955057
73.03370786516854
74.15730337078652
75.28089887640449
76.40449438202246
77.52808988764045
78.65168539325843
79.7752808988764
80.89887640449437
82.02247191011236
83.14606741573034
84.26966292134831
85.39325842696628
86.51685393258427
87.64044943820225
88.76404494382022
89.8876404494382
91.01123595505618
92.13483146067416
93.25842696629213
94.3820224719101
95.50561797752809
96.62921348314607
97.75280898876404
98.87640449438202
100.0
and it is my flask code
from flask import Flask, render_template, request
from maratang import search
app = Flask(__name__)
#app.route('/')
def test():
return render_template('post.html')
#app.route('/progress', methods=['POST', 'GET'])
def loding():
global result, path, list, error
if request.method == 'POST':
result = request.form
path = request.form['path']
list, error, rist = search(path)
return render_template('progress.html', rist = rist)
#app.route('/list', methods=['POST'])
def post():
if request.method == 'POST':
print(list)
return render_template("result.html", result = result, list = list, error = error)
if __name__ == '__main__':
app.run()
I thought it was right, but there was an error, so I don't know what to do.

Change color css div in flask python

**
This is my Flask file
**
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
return render_template("index.html")
#app.route('/play')
def bluebox():
return render_template('index.html', times=3)
#app.route('/play/<int:x>')
def second(x):
return render_template('index.html', times=x)
# #app.route('/play/<int:x>/color')
# def green(x):
# return render_template('index.html', times=x, )
if __name__ == "__main__":
app.run(debug=True)
**
This is my html file
**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
.blue {
width: 100px;
height: 100px;
background-color: lightblue;
border: 1px solid black;
margin: 20px;
display: inline-block;
}
</style>
<title>Blog</title>
</head>
<body>
{% for i in range(times): %}
<div class = "blue"></div>
{% endfor %}
</body>
</html>
with the function
#app.route('/play/<int:x>')
def second(x):
return render_template('index.html', times=x)
I created an url that when you enter localhost:5000/play/10 it will return 10 blue boxes and when you enter localhost:5000/play/30 it will return 30 blue boxes
and now i want to create a function when you enter localhost:5000/play/10/red 10 red boxes will return and localhost:5000/play/10/pink => 10 pink boxes will return. Like the url change the color. How can I do that?
Try this below in your HTML :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
<style>
.color {
width: 100px;
height: 100px;
background-color: var(--color);
border: 1px solid black;
margin: 20px;
display: inline-block
}
</style>
</head>
<body>
{% for i in range(times): %}
<div class="color" style="--color: {{ color }}"></div> ------ Pass the color dynamically
{% endfor %}
</body>
</html>
In your app.py , do this :
#app.route('/play/<int:x>/<string:color>')
def second(x, color):
return render_template('index.html', times=x, color=color)

Flask: how to update div after processing form inputs

My Flask app does calculations based on user form inputs. These calculation take about 10 seconds to complete. The output of those calculations need to be displayed in a div on the same page, next to the form (in a chart / table etc).
I have tried two aproaches. The first, using normal just Flask, reloads the whole page, which is far from ideal. The second approach, using Sijax, updates just the div. But in this case, i don't know how to access the form inputs.
I'm confused how to get this working. Would appreciate any directions!
Approach 1: just flask (downside: whole page reloads)
form_test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Testpage</title>
</head>
<body>
<form action="{{ url_for('do_the_math') }}" method="post">
A = <input type="number" name="input_A">
B = <input type="number" name="input_B">
<input type="submit" value="Submit">
</form>
<div id="destination_div">A + B = {{ result }}</div>
</body>
</html>
app_normal.py:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/")
def show_home():
return render_template("form_test.html", result='unknown yet')
#app.route("/do_the_math", methods=['POST'])
def do_the_math():
A = request.form.get('input_A')
B = request.form.get('input_B')
sum = float(A) + float(B)
# reloads whole page
return render_template("form_test.html", result=sum)
# what i want: reload just update destination_div with new HTML
# return render_template("#destination_div", "A + B = " + str(sum))
if __name__ == '__main__':
app.run(debug=True)
Approach 2: use Sijax (updates div, but how to access form inputs?)
form_test_sijax.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Testpage with sijax</title>
<script type="text/javascript" src="/static/js/sijax/sijax.js"></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
</head>
<body>
<form method="post">
A = <input type="number" name="input_A">
B = <input type="number" name="input_B">
<button type="button" onclick="Sijax.request('submit_form');">calc</button>
</form>
<div id="destination_div">A + B = unknown</div>
</body>
</html>
app_sijax.py
from flask import Flask, render_template, g
import flask_sijax
import os
app = Flask(__name__)
# init sijax
app.config["SIJAX_STATIC_PATH"] = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/')
app.config["SIJAX_JSON_URI"] = '/static/js/sijax/json2.js'
flask_sijax.Sijax(app)
def submit_form_handler(obj_response):
A = 5 # how do get to the values entered in the form?
B = 3
sum = A + B
obj_response.html("#destination_div", "A + B = " + str(sum))
#flask_sijax.route(app, "/")
def show_home():
result = 'unknown'
if g.sijax.is_sijax_request:
g.sijax.register_callback('submit_form', submit_form_handler)
return g.sijax.process_request()
return render_template("form_test_sijax.html")
if __name__ == '__main__':
app.run(debug=True)
You can use ajax with jquery to dynamically update the page with the computed result without having to refresh the page:
In the html file:
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</header>
<body>
<div class='wrapper'>
A = <input type="number" id="input_A">
B = <input type="number" id="input_B">
<button class='get_result'>Calculate</button>
<div class='result'></div>
</div>
</body>
<script>
$(document).ready(function(){
$('.wrapper').on('click', '.get_result', function(){
var val1 = $("#input_A").val();
var val2 = $("#input_B").val();
$.ajax({
url: "/calculate_result",
type: "get",
data: {val1: val1, val2:val2},
success: function(response) {
$(".result").html('<p>'+response.result.toString()+'</p>');
},
});
});
});
</script>
</html>
Then, in the main app file, create the route to calculate the final result:
#app.route('/calculate_result')
def calculate_result():
a = int(flask.request.args.get('val1'))
b = int(flask.request.args.get('val2'))
return flask.jsonify({"result":a+b})

Flask variables not showing up in HTML

I have a small flask app I am using it to:
Make an HTML page with a leaflet map
Take user input from the HTML page...
Run calculations on that input using certain python modules
Return those variable to JS functions in the page to populate the map
I cannot get ANYTHING but lat and lng to return into my HTML {{}} flask variables.
Here is my HTML page:
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css"
integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js"
integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw=="
crossorigin="">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<title>Page Title</title>
<meta charset="utf-8"/>
<style>
#mapid { height: 300px; }
</style>
<body>
<form method="POST">
Latitude to PY: <input name="lat" id="lat"/>
<br/>
Longitude to PY: <input name="lng" id="lng"/>
<br/>
<button>Get data</button>
</form>
{% if lat1 != None and lng1 != None %}
{{lat1}},{{lng1}}
<script>
var lat1 = {{lat1}}
var lng1 = {{lng1}}
</script>
{% endif %}
{% if point != None %}
<p>{{point}}</p>
{% endif %}
{% if GeJ != None %}
{{GeJ}}
<script>
var GeJ = {{GeJ}}
</script>
{% endif %}
<div id="mapid"></div>
<script>
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
maxZoom: 18,
id: 'mapbox.high-contrast',
accessToken: 'pk.eyJ1IjoiY2dyb3RoIiwiYSI6ImNqZ2w4bWY5dTFueG0zM2w0dTNkazI1aWEifQ.55SWFVBYzs08EqJHAa3AsQ'
}).addTo(mymap);
function zoomTo() {
mymap.panTo(new L.LatLng(lat1, lng1));
}
function addGJ(){
var myLayer = L.geoJson(GeJ).addTo(mymap);
}
window.onload = zoomTo();
window.onload = addGJ();
</script>
</body>
</html>
Here is my Flask Python code:
from flask import Flask, render_template, request, flash, redirect, url_for,jsonify
from forms import RegistrationForm
import json
import osmnx as ox
import networkx as nx
import matplotlib.pyplot as plt
from networkx.readwrite import json_graph
import pandas as pd
import mplleaflet
app = Flask(__name__)
app.config.update(dict(
SECRET_KEY="powerful secretkey",
WTF_CSRF_SECRET_KEY="a csrf secret key"
))
#app.route('/')
def my_form():
return render_template('map.html')
#app.route('/', methods=['GET', 'POST'])
def my_form_post():
lat = (request.form['lat'])
lng = (request.form['lng'])
lat = lat
lng = lng
point = (lat,lng)
G = ox.core.graph_from_point(point, distance = 500, network_type='walk')
fig, ax = ox.plot_graph(G)
GJ = mplleaflet.fig_to_geojson(fig=ax.figure)
#return lat, ",", lng
return render_template('map.html', lat1=lat, lng1=lng, GeJ=GJ, point="test_string")`
if __name__ == "__main__":
app.run(host='0.0.0.0',port=5000,debug=True)
The Flask app is working fine so the file structure is not a concern. I just cannot get any other variables to return into my HTML. I even tried making little string dummy variables other that the real ones. No Dice.
Thanks
You could try using the builtin none value http://jinja.pocoo.org/docs/templates/#none
Then do something like:
{% if lat1 is not none and lng1 is not none %}
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css"
integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js"
integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw=="
crossorigin="">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<title>Page Title</title>
<meta charset="utf-8"/>
<style>
#mapid { height: 300px; }
</style>
<body>
<form method="POST">
Latitude to PY: <input name="lat" id="lat"/>
<br/>
Longitude to PY: <input name="lng" id="lng"/>
<br/>
<button>Get data</button>
</form>
{% if lat1 is not Null and lng1 is not Null %}
{{lat1}},{{lng1}}
<script>
var lat1 = {{lat1}}
var lng1 = {{lng1}}
</script>
{% endif %}
{% if point != None %}
<p>{{point}}</p>
{% endif %}
{% if GeJ != None %}
{{GeJ}}
<script>
var GeJ = {{GeJ}}
</script>
{% endif %}
<div id="mapid"></div>
<script>
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
maxZoom: 18,
id: 'mapbox.high-contrast',
accessToken: 'pk.eyJ1IjoiY2dyb3RoIiwiYSI6ImNqZ2w4bWY5dTFueG0zM2w0dTNkazI1aWEifQ.55SWFVBYzs08EqJHAa3AsQ'
}).addTo(mymap);
function zoomTo() {
mymap.panTo(new L.LatLng(lat1, lng1));
}
function addGJ(){
var myLayer = L.geoJson(GeJ).addTo(mymap);
}
window.onload = zoomTo();
window.onload = addGJ();
</script>
</body>
</html>
It would help if you provided an example of what exactly happens when you pass all the values.
Otherwise, what according to me, could be causing the problem is that the 'Null' object in python is the singleton None. The best way to check things for "Noneness" is to use is not None or better still, something as simple as:
{%if lat%} {{lat}} {% endif %}
Also, can't you assign GeJ to the var GeJ within the div instead of putting a line of JS in an abrupt manner up there?
P.S. I wanted to add this as a comment, but don't have enough reputation. Apologies.

Categories

Resources