How to update content without reloading an HTML page?

Asked

Viewed 1,600 times

3

I built a Flask API connected to a Mysql database, which has its entries displayed in an HTML page.

player_manager.py:

from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql+pymysql://xre:sdhjsdhsj2562@localhost:3306/team'

db = SQLAlchemy(app)

@app.route("/", methods=["GET"])
def get():
    try:
        players = Player.query.all()
    except Exception as e:
            print("Failed")
            print(e)
    return render_template("home.html", players=players)

@app.route("/", methods=["POST"])
def post():
    player = Player(
        nome=request.args.get("nome"), 
        posicao=request.args.get("posicao"),
        numero=request.args.get("numero"),
        gols=request.args.get("gols"),
        partidas=request.args.get("partidas"))
    db.session.add(player)
    db.session.commit()
    return redirect("/")



class Player(db.Model):
    nome = db.Column(db.String(80), unique=True, nullable=False, primary_key=False)
    numero = db.Column(db.Integer, primary_key=True)
    posicao = db.Column(db.String(80), unique=True, nullable=False, primary_key=False)
    gols = db.Column(db.Integer, primary_key=False)
    partidas = db.Column(db.Integer, primary_key=False)

    def __repr__(self):
        return "Nome: {}, Numero: {}, Posicao: {}, Gols: {}, Partidas: {}".format(
            self.nome, 
            self.numero, 
            self.posicao,
            self.gols,
            self.partidas
            )


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

home html.:

<html>
  <body>
    <h1>Jogadores</h1>
    {% for player in players %}
      <p>{{player}}</p>
    {% endfor %}
  </body>
</html>
  </body>
</html>

I would like the page displaying bank entries to be automatically updated as new entries are added to the bank. From what I researched, it would be possible to achieve this result through Server Sent Event, as in this example, or through AJAX, such as in this another example. As I’m new to web development, I don’t know how to implement these changes in my code.

Attempt to use Ajax:

player_manager.py:

@app.route("/", methods=["POST"])
def post():
    player = Player(
        nome=request.args.get("nome"), 
        posicao=request.args.get("posicao"),
        numero=request.args.get("numero"),
        gols=request.args.get("gols"),
        partidas=request.args.get("partidas"))
    db.session.add(player)
    db.session.commit()
    return redirect("/")

home html.:

<html>
  <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript">
        var new_players = $(this).val();

        $.ajax({
      url: "/",
      type: "get",
      data: {jsdata: new_players},
      success: function(response) {
        $("#players_list").html(response);
      },
      error: function(xhr) {
        //Do Something to handle error
      }
    });
    </script>
    <div id="players_list">
        <h1>Jogadores</h1>
    {% for player in players %}
      <p>{{player}}</p>
    {% endfor %}
    </div>
  </body>
</html>
  </body>
</html>

However, I still can’t update the content without reloading the content.

1 answer

0

Well, you really need to use something other than Flask himself for this task and Ajax is a good solution. However, the data update must occur given some event. Since you need a full-time update, you can set a timeout (you have an example here). The way you did the function is only called once, when the page is loaded.

However, I would advise something more robust. You can think of solutions using the React and even change its basis to the Firebase, for example (you can only evaluate to see if it’s worth it). Flask’s Jinja2 is very good and has a lot going for it, but you’ll always need something else and this can be achieved by merging technologies. Type embedding Javascript scripts, using Vue.js, etc.

Anyway, this is it. Good luck on your project!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.