It’s an error I’ve been stuck on for a while.
var longitude = 20
How would I pass this to python with Flask without using any complicated GET/POST requests? My end goal is to print the statement in the python console.
print(getfromjavascript(longitude))
Pseudocode
Advertisement
Answer
Ok, there is a lot to learn, but an example made everything better to understand:
app.py
from flask import Flask, request, render_template app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': print(request.form.get('longitude')) return render_template('index.html') if __name__ == '__main__': app.run()
templates/index.html
<form method="POST" action=""> <input type="text" name="longitude" /> <input type="submit" value="Submit" /> </form> <script> var longitude = 20; var request = new XMLHttpRequest(); request.open('POST', '/', true); request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); request.onreadystatechange = function() { // do something }; request.send('longitude=' + longitude); </script>
This simple code will print the longitute value when you click in the button only on console, but also triggers a post request from Javascript that will do the same automatically every time you access the page.