cracka31 cracka31 - 3 years ago 148
Ajax Question

Incrementing variable in AJAX and Flask while automatically reloading

I'm using

function to reload information every 5 seconds. The html looks like:

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

function() {
}, 5000);

In Flask, my

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
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, here are the modifications you should be doing


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

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

from flask import request

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