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

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

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