• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

148
Vistas
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 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda