Reputation:
So I've been trying to get this to work with Ajax and JQuery, but I can't seem to get it. I'm new to both of these. Sorry if this is trivial, I've been searching and working off previous answers for awhile now.
Info:
I have a Jinja tag in my page html that I would like to update once per second:
<pre id="#system_info_tag">{{ system_info_text }}</pre>
The information is originally (and successfully) populated from my main python script in a larger function called get_system_info():
@app.route('/')
def root():
return render_template('system_info.html', system_info_text=get_system_info())
I would like the element to automatically reload once per second though, so I am trying to do that with JS as follows (which I thought would re-run my python function, as re-loading the page updates it):
function() {
setInterval(function() {
$("#system_info_tag").load(location.href + " #system_info_tag");
}, 1000);
});
which is loaded in my html file with:
<script src="static/js/update_refresh.js"></script>
The page loads fine with the correct information, but the element doesn't auto-reload. Any help would be much appreciated.
Upvotes: 0
Views: 3562
Reputation: 113988
main.py
@app.route('/')
def root():
return render_template('system_info.html', system_info_text=get_system_info())
@app.route("/sys_info.json")
def system_info(): # you need an endpoint on the server that returns your info...
return get_system_info()
templates/system_info.html
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<div id="content">{{ system_info }}</div> {# this is the original system_info passed in from the root view #}
<script>
setInterval(function(){ // load the data from your endpoint into the div
$("#content").load("/sys_info.json")
},1000)
</script>
I think anyway
Upvotes: 1
Reputation: 91555
The self-invoking function you've wrapped your script in isn't being called. It should be:
(function() {
// your code
})();
Note the extra ()
at the end. That's what's actually calling that function that's defined inside the previous parenthesis.
Next, in your HTML, remove the #
from your id
on the <pre>
tag. The #
is only used in selectors, not actual attributes.
<pre id="system_info_tag">{{ system_info_text }}</pre>
Next, remove the space from the beginning of your anchor you're appending to the URL.
location.href + '#system_info_tag'
Finally, check your Network tab in your browser's dev tools to see if those load()
requests are even firing. If they are, see which URL they're calling. There is a good chance they're hitting the wrong URL and won't load anything as a result.
Upvotes: 0