-4

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

  • 5
    You certainly need to make a request, whether "complicated" or not. JS runs on the client, Python/Flask on the server, the only way to communicate from client to server is via an HTTP request. This is kind of fundamental to how the web works :) – Robin Zigmond Mar 18 '21 at 23:05
  • I'm very new to Flask. Would you mind elaborating? – user15426564 Mar 18 '21 at 23:06
  • 1
    Nothing to do with Flask specifically - you need to learn the basics of the client/server architecture by the sound of it. [This question](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) and its answers may help. – Robin Zigmond Mar 18 '21 at 23:13
  • For Flask itself, if you are new to it, I recommend going through the [Flask tutorial](https://flask.palletsprojects.com/en/1.1.x/tutorial/). There's a section there where it receives a request from the UI/frontend: https://flask.palletsprojects.com/en/1.1.x/tutorial/views/#the-first-view-register. You need to set up something similar: send the variable value in a request, receive the request on the backend, and then you can do whatever you want with the received value. There is no way around making a request. – Gino Mempin Mar 19 '21 at 00:15

1 Answers1

-1

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.

Hector Vido
  • 765
  • 5
  • 12