0

I'm using setInterval() function to reload information every 5 seconds. The html looks like:

<div id = "update"> </div>

<script>
window.setInterval(
     function() {
     $("#update").load("/game");
     }, 5000);
</script>

In Flask, my views.py:

@app.route('/game')
def live_game():
   text = "<p> test </p>"
   return text

Now, I'd like to change the variable text every time the page reloads. Something like:

counter = 0
@app.route('/game')
def live_game():
   textlist = ['a','b','c','d']         
   text = "<p> "+textlist[counter]+" </p>"
   counter += 1

   return text

This obviously doesn't work, as I'm sure I need to be incrementing on the jQuery side, I'm just not sure how. Any help would be appreciated!

2 Answers 2

1

To make it work you need to modify your JavaScript as well as your views.py, here are the modifications you should be doing

HTML

<div id = "update"> </div>

<script type="text/javascript">
   var counter = 0;
   window.setInterval(function(){
      $("#update").load("/game?counter=" + counter);
      counter++;
   }, 5000)

views.py

from flask import request

@app.route("/game")
def live_game():
    textlist = ['a','b','c','d']
    counter = request.args.get('counter')
    return "<p> " + textlist[counter] + " </p>"

The output will be

<div id = "update"><p> a </p></div>
// after 5 seconds 
<div id = "update"><p> b </p></div>
// and so on

Let me know if you still face any issue.

Have fun :)

Sign up to request clarification or add additional context in comments.

Comments

0

You need to call the /game flask endpoint in your setInterval function. Here is much what you need.

<script>
window.setInterval(
     function() {
         $.ajax("/game", {dataType:'text', cache: false}).done(function(data){
            $("#update").html(data);}
        );
     }, 5000);
</script>

The method will update with whatever the /game endpoint returns. It is unclear what you intend to be updating or incrementing.

2 Comments

Thanks for the answer. I'm unclear on how this increments through the text list. Do I need to update the function in views.py as well?
Your existing view code should increment through the test list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.