Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
Passing variable from JavaScript to flask route

I need help in sending data from variable derived in JavaScript to flaks route. I have submit button, on which I have flask route and I am passing variables encloses in {{}}.

One of the variable selectedItem is derived inside JavaScript. I get right value on alert but when route is called it’s coming as None. Am I doing something wrong here? May be html submit is not able to refer to JavaScript variable? If I pass hardcoded value to my route parameter it works fine.

Please help. Thank you

function test_alert(e){ alert("tis is test"+e.value) selectedItem=e.value; }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you want to transfer your javascript variable to your flask route kindly check my answer here:

Why does my data come from request.form when passing it to the backend in Flask, python?

  1. Ajax/Fetch

JavaScript

var your_data = {

/* name */ : /* value */
}


  fetch(`${window.origin}/your_url`, {
    method: "POST",
    credentials: "include",
    body: JSON.stringify(your_data),
    cache: "no-cache",
    headers: new Headers({
      "content-type": "application/json"
    })
  })

Python

@app.route("/your_url", methods = ["post"])
def printer():
  data = request.get_json()
  print(data)
  return "TODO"

However if you want to render a template (like a form submit would do) then you can do this:

A. Doing it inside a hidden form

HTML


<form id="mainform" action="/your_url" method="post">
  <input type="hidden" name="jsvar" id="jsvar" value="" />
  <button type="submit">Click Me</button>
</form>

JavaScript

var form = document.getElementById("mainform")
      var input = document.getElementById("jsvar")
      form.addEventListener('submit', function(e){
        input.value = "your_var"
        form.submit()
      })

Python


@app.route("/test",methods=["POST"]) 
def proposeswap_db_function():
  print("inside function") 
  data = request.form["jsvar"]
  print(data) 
  print('rendering mainmenu') 

  return f"{data}"

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!