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

322
Visualizações
Dynamically Update Divs on Webpage (flask)

Dynamically Update Divs on Webpage

I am trying to update a webpage dynamically using flask and JavaScript (AJAX). I would like to update the scores for both teams without refreshing the page (At a set interval). The problem that I am having is that the div scores, in the 'updated_score_div.html' page seem to be appending instead of replacing the div scores in the 'home.html page'. Is there a way to avoid this? (By changing the AJAX code or using fetch?)
Ideally I would like to do this for multiple teams that are in different div's on webpage.

flask code:

from flask import Flask, redirect, url_for, render_template, jsonify

app = Flask(__name__)

@app.route("/updated_score_divs", methods = ['POST'])
  def updatescoredivs():

    teamonescore = '20'
    teamtwoscore  = '15'

  return jsonify('', render_template("updated_score_divs.html", x = teamonescore, y = 
teamtwoscore))

@app.route("/")
  def homepage():
    teamonescore = '00'
    teamtwoscore = '00'
  return render_template("home.html", x = teamonescore, y = teamtwoscore)

if __name__ == "__main__":
    app.run(debug=True)

home.html code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script>
$(function(){
    window.setInterval(function(){
        loadNewScore()
    }, 3000)

function loadNewScore(){
    $.ajax({
        url: "/updated_score_divs",
        type: "POST",
        dataType: "json",
        success: [code1, code2] 
        }) 
    }     
});

function code1(data){$(teamonescore).replaceWith(data)}
function code2(data){$(teamtwoscore).replaceWith(data)}

</script>

<h1>Home Html</h1>

This is the Team One Score
<div id = "teamonescore">
    {{x}}
</div>
This is the Team Two Score
<div id = "teamtwoscore">
    {{y}}
</div>

updated_score_divs.html code:

<div id = "teamonescore">
    {{x}}
</div>

<div id = "teamtwoscore">
    {{y}}
</div>

Initial Homepage
Updated Homepage

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The issue is with your logic. The function updatescoredivs provides values for both teamone and teamtwo and both these values are output to your template via the render_template command. This means that your template - updated_score_divs.html code actually has the 2 scores.

Then you replace contents of teamonescore with the template (remember it already has the 2 values) and then replace contents of teamtwoscore with the same template. You thus get the template repeated (so it looks like an Append)

2)

Instead of doing a return render_template in the function updatescoredivs, you should just return json e.g.

return jsonify(x = teamonescore, y = teamtwoscore)
about 4 years ago · Juan Pablo Isaza Relatório

0

with jquery...

// pass an ElementID and an endpoint to redraw that div with the endpoints response
window.redraw = function( _id, endpoint ){
    $.get( endpoint, function( data ) {
    $( "#"+_id ).html( $(data).html() );
    });
}

with fetch...

function redraw(_id, endpoint) {
  fetch(endpoint)
    .then(function(response){return response.text();})
    .then(function(data){
            document.getElementById(_id).innerHTML = data;
        }
    )
}

consider also htmx to hide all that... https://htmx.org/

and don't return json. return html. it's fine.

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