Home > front end >  Passing variable from JavaScript to flask route
Passing variable from JavaScript to flask route

Time:04-19

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

CodePudding user response:

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}"

  • Related