cracka31 cracka31 - 3 years ago 148
Ajax Question

Incrementing variable in AJAX and Flask while automatically reloading

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!

Answer Source

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 :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download