ajax – How to update content without reloading HTML page?

Question:

I set up 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 that displays the bank's 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, as in this other example. As I'm new to web development, I don't know how to implement these changes in my code.

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

Answer:

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

However, I would advise something more robust. You can think of solutions using React and even change your base to Firebase , for example (you can just evaluate to see if it's worth it). Flask's Jinja2 is very good and has a lot, but you will always need something more and this can be achieved by mixing technologies. Type embedding JavaScript scripts, using Vue.js, etc.

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

Scroll to Top
AllEscort