Home > front end >  Dynamically Update Divs on Webpage (flask)
Dynamically Update Divs on Webpage (flask)

Time:10-27

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

CodePudding user response:

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)

CodePudding user response:

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.

  • Related