Draco Malfago
Draco Malfago

Reputation: 323

create dynamically html div jinja2 and ajax

So I have this scroll function that sends an ajax request when it hits the bottom of the page, the ajax function retrieves some data in JSON, I want to populate this data into a div. Is it possible to use jinja2 to do this? At the moment I am just playing around and creating a div (not the one I want) with js.

<script type="text/javascript">
    $(document).ready(function() {
        var start = $(".boxybox").length;
        var stop = start + 3;

        var create_div = function() {
            if ($(window).scrollTop() === $(document).height() - $(window).height()) {
              $.get('/more', {
                  start: start,
                  stop: stop
                  }, function(feed) {
                    var feed = JSON.parse(feed);
                    console.log(feed[0].limit);
                    var div = $("<div></div>").addClass("boxybox").attr("id", feed[0].limit);
                    $('.feed').append(div);
                  });
            }
        }
        var throttled = _.throttle(create_div, 500);
        $(window).scroll(throttled);
    });
</script>

This does the job, but I am interesting if I can create this div dynamically with jinja2 and plain HTML instead?

I have thought of 3 options to do this, first is what I showed, 2nd would be to create the HTML server side and return in JSON and 3rd would be somehow use jinja2 and populate div?

Upvotes: 4

Views: 6396

Answers (1)

Michael Yousrie
Michael Yousrie

Reputation: 1142

Okay, this is a bit complicated but I hope I understood it right.

Yes, you can use Jinja2 to create dynamic stuff with ajax.

Simply, create a new HTML file and add the jinja templating to it ( like u did ) then send the request to a view function in the views file and make that function return render_template('path/to/dynamic_data.html', new_fetched_data=new_fetched_data) then append the result via jQuery.

Too much talk, let's write some code.

Example Code

dynamic_data.html

{% block body %}
    <div class="new_dynamic_data">
        {% if new_fetched_data %}
             <p> {{ new_fetched_data }} </p>
             # Do whatever with the data
        {% endif %}
    </div>
{% endblock %}

views.py

@app.route('/more/', methods=['POST'])
def _more():
    new_fetched_data = fetch_data() # Data fetch function through sqlalchemy
    return jsonify('fetched_data', render_template('dynamic_data.html', new_fetched_data=new_fetched_data))

application.js

#Function to handle scrolling
$.ajax({
    url: "/more/",
    type: "POST",
    dataType: "json",
    success: function(data){
         $(html).append(data);
    }
});

if you are still confused, leave a comment and I will reply.

Upvotes: 6

Related Questions