I take some user input that results in a table which I can display. Now I want to allow the user to select some data and then send these data back to another function where it is further processed. For the toy example I use for demonstration purposes, it might look like this:
Unfortunately, I fail to do so. The critical parts are probably thisjquery part (the entire code can be found below):
$('#send_data').bind('click', function() {
$.getJSON('/_selected_data', {
sel_data: table.rows().data().toArray()
}, function(data) {
alert('This worked')
});
return false;
});
and this part of my Python code:
#app.route('/_selected_data')
def get_selected_data():
sel_data = request.args.get('sel_data')
When I print sel_data it prints None, when I use requests.json it does not work either; ideally it would be possible to get the results again as a pandas dataframe with the same columns headers.
How would I do this correctly? Also, if the user does not select any data, then of course the entire table should be returned.
This is the entire code:
from flask import Flask, render_template, request, jsonify
import pandas as pd
import numpy as np
import json
# just for reproducibility
np.random.seed(0)
# Initialize the Flask application
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/_get_table')
def get_table():
a = request.args.get('a', type=int)
b = request.args.get('b', type=int)
df = pd.DataFrame(np.random.randint(0, 100, size=(a, b)), columns=['C1', 'C2'])
return jsonify(number_elements=a * b,
my_table=json.loads(df.to_json(orient="split"))["data"],
columns=[{"title": str(col)} for col in json.loads(df.to_json(orient="split"))["columns"]])
#app.route('/_selected_data')
def get_selected_data():
sel_data = request.args.get('sel_data')
print(sel_data)
return jsonify(dummy_data=1)
if __name__ == '__main__':
app.run(debug=True)
and my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">Create a pretty table</h3>
</div>
<div>
<p>Number of rows</p>
<input type="text" size="5" id="a" value="10">
<p>Number of columns</p>
<input type="text" size="5" id="b" value="2">
<p>get a pretty table</p>
<p>send selected data</p>
<p>Result</p>
<p>Number of elements:</p>
<span id="elements">Hallo</span><br>
<table id="a_nice_table" class="table table-striped">Here should be a table</table>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var table = null;
$('#calculate').bind('click', function() {
$.getJSON('/_get_table', {
a: $('#a').val(),
b: $('#b').val()
}, function(data) {
$("#elements").text(data.number_elements);
if (table !== null) {
table.destroy();
table = null;
$("#a_nice_table").empty();
}
table = $("#a_nice_table").DataTable({
data: data.my_table,
columns: data.columns
});
});
return false;
});
$('#send_data').bind('click', function() {
$.getJSON('/_selected_data', {
sel_data: table.rows().data().toArray()
}, function(data) {
alert('This worked')
});
return false;
});
});
</script>
</body>
</html>
Here is my attempted solution to your problem. I'm making the assumption that the user can only select one row at a time.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">Create a pretty table</h3>
</div>
<div>
<p>Number of rows</p>
<input type="text" size="5" id="a" value="10">
<p>Number of columns</p>
<input type="text" size="5" id="b" value="2">
<p>get a pretty table</p>
<p>send selected data</p>
<p>Result</p>
<p>Number of elements:</p>
<span id="elements">Hallo</span><br>
<table id="a_nice_table" class="table table-striped">Here should be a table</table>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var table = null;
var selected = null;
$('#calculate').bind('click', function() {
$.getJSON('/_get_table', {
a: $('#a').val(),
b: $('#b').val()
}, function(data) {
$("#elements").text(data.number_elements);
if (table !== null) {
table.destroy();
table = null;
$("#a_nice_table").empty();
}
table = $("#a_nice_table").DataTable({
data: data.my_table,
columns: data.columns
});
var drawn_table = document.getElementById('a_nice_table'),
selected = drawn_table.getElementsByClassName('selected');
drawn_table.onclick = highlight;
function highlight(e) {
if (selected[0]) selected[0].className = '';
e.target.parentNode.className = 'selected';
}
});
return false;
});
$('#send_data').bind('click', function() {
var selected = $("tr.selected").html();
if (selected != null) {
console.log("<thead>" + $("#a_nice_table thead").html() + "</thead><tbody><tr>" + selected + "</tr></tbody>");
$.getJSON('/_selected_data', {
sel_data: "<thead>" + $("#a_nice_table thead").html() + "</thead><tbody><tr>" + selected + "</tr></tbody>"
}, function(data) {
alert('This worked');
});
} else {
console.log($("#a_nice_table").html());
$.getJSON('/_selected_data', {
sel_data: $("#a_nice_table").html()
}, function(data) {
alert('This worked');
});
}
return false;
});
});
</script>
</body>
</html>
app.py
from flask import Flask, render_template, request, jsonify
import pandas as pd
import numpy as np
import json
# just for reproducibility
np.random.seed(0)
# Initialize the Flask application
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/_get_table')
def get_table():
a = request.args.get('a', type=int)
b = request.args.get('b', type=int)
df = pd.DataFrame(np.random.randint(0, 100, size=(a, b)), columns=['C1', 'C2'])
return jsonify(number_elements=a * b,
my_table=json.loads(df.to_json(orient="split"))["data"],
columns=[{"title": str(col)} for col in json.loads(df.to_json(orient="split"))["columns"]])
#app.route('/_selected_data')
def get_selected_data():
sel_data = request.args.get('sel_data')
df_list = pd.read_html("<table>" + sel_data + "</table>")
df = pd.concat(df_list)
print(df)
return jsonify(dummy_data=1)
if __name__ == '__main__':
app.run(debug=True)
So basically what happens is that after a table is randomly generated, I have to create a couple of variables (drawn_table and selected) to track the table and its selected row. As of now, there's no visual change to when a row is selected but it's up to you if you want to make any CSS modifications to denote when a row is selected. When a user does click a row, the row gets a class assignment of "selected", and any other row gets deselected. This is so that JQuery will know what row is selected when sending it back to the server.
Then in the send_data link, I'll find the tr (table row) element that has the "selected" class (tr.selected) and grab the html code inside this element. If the element exists, then I will send the html along with the table header info as JSON to flask. If there is no tr.selected element, then the html code is obviously undefined, so the code will run the else part of the block and send the entire table.
In app.py, I read the JSON value, which is a string of HTML code. Since Pandas has a read_html method, I can pass the HTML string to the method to create a list of dataframes. Then I concat the list of dataframes to make my final df.
You can see the result of the dataframe in Python's console log (print(df)). You can also see the html code result in your browsers inspector because I added some console.log statements.
Related
The current camera scans the QR code and posts the same value to view_nurse.py multiple times till the QR code is moved away from the camera. This causes my database to have many repeated values shown in the image below. How do I prevent this from happening?
In situations where I scan another QR code without relaunching the camera, the program should be able to detect that it is a new QR code and POST the results into the views_nurse.py.
<nurse_home.html>
{% load static %}
{% block mainbody %}
<title>Django Online Barcode Reader</title>
<meta charset="utf-8">
{% csrf_token %}
<script src={% static "js/html5-qrcode.min.js" %}></script>
<style>
.result{
background-color: green;
color:#fff;
padding:20px;
}
.row{
display:flex;
}
</style>
<!--<form action="" method="POST">-->
{% csrf_token %}
<div class="row">
<div class="col">
<div style="width:500px;" id="reader"></div>
</div>
<div class="col" style="padding:30px;">
<h4>Scanned Result</h4>
<!--<div id="result" name="result">Result Here</div>-->
<output type="POST" id="result" name="result" placeholder="qrCodeMessage">
{% csrf_token %}
</div>
</div>
<script type="text/javascript">
// 1) Create a function to get the CSRF token
function getCookie(name) {
let cookie = document.cookie.match("(^|;) ?" + name + "=([^;]*)(;|$)");
return cookie ? cookie[2] : null;
}
// 2) After generating the qrcode in the onScanSuccess callback, you invoke sendQrCode function with the qr code as argument
function onScanSuccess(qrCodeMessage) {
document.getElementById("result").innerHTML = '<span class="result">' + qrCodeMessage + "</span>";
// Call the function here
sendQrCode(qrCodeMessage);
}
//3) Fetch to send a POST request to nurse_qrscan route:
async function sendQrCode(qrCode) {
console.log(qrCode)
const response = await fetch("/nurse_qrscan", {
method: "POST",
headers: {
"X-CSRFToken": getCookie("csrftoken"),
},
body: JSON.stringify({
result: qrCode,
}),
})
.then((response) => response.json())
.then((data) => {
console.log(data)
}
);
}
function onScanError(errorMessage) {
//handle scan error
}
var html5QrcodeScanner = new Html5QrcodeScanner("reader", {
fps: 10,
qrbox: 250,
});
html5QrcodeScanner.render(onScanSuccess, onScanError);
</script>
{% endblock %}
<view_nurse.py>
#api_view(['GET',"POST"])
# Nurse scans QR
def nurse_qrscan(request):
if request.method == 'POST':
# parse the JSON data
data = json.load(request)
result = data.get("result")
if result != None:
c = connection.cursor()
# Saving the result to database, nurse_QR
c.execute("INSERT INTO nurse_QR (output) VALUES ('{0}');".format(result))
return Action.success()
<Image: Output shown in database - Values of the single QR code is repeated multiple times from the POSTS>
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>
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.
Hello guys i have a html program in which i'm Moving the Items from One Multi Select List To Another using jQuery which is written like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> upload </title>
</head>
<script>
$(function () {
function moveItems(origin, dest) {
$(origin).find(':selected').appendTo(dest);
}
function moveAllItems(origin, dest) {
$(origin).children().appendTo(dest);
}
$('#left').click(function () {
moveItems('#sbTwo', '#sbOne');
});
$('#right').on('click', function () {
moveItems('#sbOne', '#sbTwo');
});
$('#leftall').on('click', function () {
moveAllItems('#sbTwo', '#sbOne');
});
$('#rightall').on('click', function () {
moveAllItems('#sbOne', '#sbTwo');
});
});
</script>
<body>
<div class="container">
<h1>Large Data Generation</h1>
</div>
<h2>Move Items From One List to Another</h2>
<select id="sbOne" multiple="multiple">
<option value="1">Alpha</option>
<option value="2">Beta</option>
<option value="3">Gamma</option>
<option value="4">Delta</option>
<option value="5">Epsilon</option>
</select>
<select id="sbTwo" multiple="multiple">
<option value="6">Zeta</option>
<option value="7">Eta</option>
</select>
<br />
<input type="button" id="left" value="<" />
<input type="button" id="right" value=">" />
<input type="button" id="leftall" value="<<" />
<input type="button" id="rightall" value=">>" />
</body>
</html>
In this i'm able to move the items from one multi select to another but i want don't want to Hard code the items names i want it to read through the csv file and take the header columns of the csv file
This is the csv file:
with open("Data_Large2.csv", "rt") as f:
reader = csv.reader(f)
HeaderName = next(reader)
print("HeaderName-",HeaderName)
output:
['Asset_Id',
'Asset Family',
'Asset Name',
'Location',
'Asset Component']
This is the Header column name which I want to populate in place of Alpha, Beta..not there values which I have taken Is there any way to get the headers of the column from CSV file in jquery please help me ..thnx in advance
I don't know what exactly you are searching for but i assume that you are reading a csv file from web and you can also select more than one csv file For that i have made some change in your program : Note: Here i have change the "sbone" to "sourceHeaderFields" and "sbTwo" to "targetHeaderFields"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> upload </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link href="https://bootswatch.com/4/solar/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<script>
$(function () {
function moveItems(origin, dest) {
$(origin).find(':selected').appendTo(dest);
}
function moveAllItems(origin, dest) {
$(origin).children().appendTo(dest);
}
$('#left').click(function () {
moveItems('#targetHeaderFields', '#sourceHeaderFields');
});
$('#right').on('click', function () {
moveItems('#sourceHeaderFields', '#targetHeaderFields');
});
$('#leftall').on('click', function () {
moveAllItems('#targetHeaderFields', '#sourceHeaderFields');
});
$('#rightall').on('click', function () {
moveAllItems('#sourceHeaderFields', '#targetHeaderFields');
});
$('#populateHeaderFields').on('click', function () {
alert("Inside populate list");
var files = ('#source_fileName').files;
alert("Files Count - "+ files);
});
$('#upload-form').on('change', function(evt) {
var filesCount = evt.target.files.length;
for (i = 0; i < filesCount; i++) {
var file = evt.target.files[i];
if (file) {
var reader = new FileReader();
// Read our file to an ArrayBuffer
reader.readAsArrayBuffer(file);
// Handler for onloadend event. Triggered each time the reading operation is completed (success or failure)
reader.onloadend = function (evt) {
// Get the Array Buffer
var data = evt.target.result;
// Grab our byte length
var byteLength = data.byteLength;
// Convert to conventional array, so we can iterate though it
var ui8a = new Uint8Array(data, 0);
// Used to store each character that makes up CSV header
var headerString = '';
// Iterate through each character in our Array
for (var i = 0; i < byteLength; i++) {
// Get the character for the current iteration
var char = String.fromCharCode(ui8a[i]);
// Check if the char is a new line
if (char.match(/[^\r\n]+/g) !== null) {
// Not a new line so lets append it to our header string and keep processing
headerString += char;
} else {
// We found a new line character, stop processing
break;
}
}
//Iterate through the list and populate the select element..
$.each(headerString.split(","), function(i,e){
$("#sourceHeaderFields").append($("<option>", {
text: e,
value: e
}));
});
console.log(headerString);
console.log("Next Read");
};
} else {
alert("Failed to load file");
}
}
});
});
</script>
<body>
<div class="container">
<h1>Large Data Generation</h1>
</div>
<form id = "upload-form" action="{{ url_for('upload') }}" method="POST" enctype="multipart/form-data">
<div id="file-selector">
<p>
<strong>Input File: </strong>
<input id="source_fileName" type="file" name="source_fileName" accept="csv/*" multiple >
</p>
</div>
<h2>Move Items From One List to Another</h2>
<select id="sourceHeaderFields" multiple="multiple">
</select>
<select id="targetHeaderFields" multiple="multiple">
</select>
<br />
<input type="button" id="left" value="<" />
<input type="button" id="right" value=">" />
<input type="button" id="leftall" value="<<" />
<input type="button" id="rightall" value=">>" />
</body>
</html>
I think this will help you get what you need
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.