Christopher Nelson Christopher Nelson - 9 months ago 71
Python Question

JQuery to reload DIV? (Flask/Jinja2)

I've searched to no avail.. I guess my question is a bit unique. I have a DIV with some content in it, that content get's brought in currently by passing the object of a SQL query into the template. That works fine, but doesn't allow me to update the content every x seconds, without refreshing the entire page. Something I don't want to do. So I wanted to know I could force JQuery to reload my DIV element? Would this also reload the code in it? Because that would force my div to update.. Here is the code.

<div id=content1>
{{ set content = get_content(parm1, parm2) }} # This is a custom Jinja2 function I wrote to pull the content I need one in the template, but it only runs once.
{% for row in content %}
.. do stuff
{% endfor %}
</div>


Is it possible to get JQuery to just reload that DIV with the code that is already there? If so that should fix my issue. I have thought about trying to create a call to get the content in JSON but IF possible would rather not.

Answer Source

app.py

@app.route('/')
def some_view():
    name = request.args.get('name', 'Anonymous')
    if request.is_xhr:
        template_name = 'template_ajax.html'
    else:
        template_name = 'template.html'
    return render_template(template_name, name=name)

template.html

<html>
    <head>
        <title>Test</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <head>
    <body>
        <h3>Title</h3>
        <div>Hello, {{ name }}!</div>
        <p>Some text</p>

        <script>
            $(document).ready(function() {
                $('div').load('/?name=username');
            });        
        </script>
    </body>
</html>

template_ajax.html

Hello from AJAX, {{ name }}!