Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

482
Vistas
Pass variables from Flask (Python) to Javascript in a Separate JS file via AJAX

I'm in the learning stages so please bear with me. I've been trying to get answers but often its type="POST" from JS to Flask via AJAX.

This is my app.py.

@app.route("/dashboard", methods=["GET","POST"]);
def dashboard():
    yearCount = #Sample list of dict data
    return render_template("dashboard.html", yearCount=yearCount)

(edit) How do I get yearCount from above and pass it to a javascript via AJAX? yearCount will be loaded when dashboard.html renders.

This is my js

$.ajax({
  url: '/dashboard',
  type: "GET",
  // data: "How do I get the data yearCount from /dashboard?",
  success: function() {
    alert(this.url);
  }
});

I really appreciate the help! Been tearing my hair out figuratively the whole week trying to look for answers.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Transfer of variables during the rendering process from the template:
You can pass the variable on as json with the jinja filter tojson. If you need the variable outside of your template, you have to pass it as a parameter.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <script type="text/javascript">
      const yearCount = {{ yearCount | tojson }};
      console.log(yearCount);
    </script>
  </body>
</html>

Loading data while the page is already shown in the browser:
If you want to receive the variable again after the template has been rendered, ajax is the right choice.

from flask import jsonify

@app.route('/count')
def count():
    yearCount = # your dict data here.
    return jsonify(yearCount)

In your example code you are using the jQuery library. However, implementation with the help of the fetch api is also possible. The following is an example of each.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    <!-- Load the jQuery library. -->
    <script 
      src="https://code.jquery.com/jquery-3.6.0.min.js" 
      integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" 
      crossorigin="anonymous"></script>
    <!-- Use the jQuery library to load data with ajax. -->
    <script type="text/javascript">
      // jQuery ajax
      $.ajax({
        url: '/count'
      }).done((data) => {
        console.log(data);
      });
    </script>


    <!-- The fetch api does not require any additional library. -->
    <script type="text/javascript">
      // fetch api
      fetch('/count')
        .then(resp => resp.json())
        .then(data => console.log(data));
    </script>

  </body>
</html>
about 4 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 Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda