2

I want to send this variable value in python variable to perform different tasks.

var d="string"

I don't want to send variable values through URL. I want to use some like this code.

@app.route("/", methods=['POST'])
def hello1():
    d = request.form['n'] #here i take value from name of html element
1
  • You cos for example send it via a form or an ajax call Commented Mar 1, 2019 at 0:20

2 Answers 2

1

use an AJAX post.

let myVar = 'Hello'
$.post('http://localhost:5000/getjs', {myVar}, function(){
    // Do something once posted.
})

and your Flask will be something like this

@app.route('/getjs', methods=['POST'])
def get_js():
    if request.method == 'post':
        js_variable = request.form
        return js_variable

Alternatively you can do this:

@app.route('/getjs/<variable>')
    def get_js(variable):
        js_variable = variable
        return js_variable

so when you direct your url to http://localhost:5000/getjs/apples js_variable will be 'apples'

Sign up to request clarification or add additional context in comments.

4 Comments

fixed. this is just off the top of my head, but its methods I use to send data from JS to backend Flask
you should really use jsonify for responses back into ajax calls. See flask docs example.
We're not here to hold hands, just point people in the right direction
Please provide an answer then, thats the whole point of this isn't it?
0

Use native javascript 'fetch'.

Ari Victor's solution requires an external library: jquery

var url = 'http://localhost:5000/getjs';
var data = {field_name: 'field_value'};

fetch(url, {
  method: 'POST',
  body: JSON.stringify(data), 
  headers:{
    'Content-Type': 'application/json'
  }
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.