Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda