Saad Khan
Saad Khan

Reputation: 31

how to pass JavaScript variable value into python variable(flask)

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

Upvotes: 2

Views: 1850

Answers (2)

balderman
balderman

Reputation: 23815

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));

Upvotes: 0

Ari
Ari

Reputation: 6149

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'

Upvotes: 1

Related Questions