Draco Malfago Draco Malfago - 19 days ago 5
Python Question

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?

<div class='boxybox' id='{{ item.id }}'>
<form name="poll" id='{{ item.id }}' method="post" action='/poll'>
<label class='lab-pos'>
<input type="radio" name="points" id='whine-pos' value=1>
<img class='img-pos'src="/static/pic.png">
</label>
<label class='lab-neg'>
<input type="radio" name="points" id='whine-neg' value=-1>
<img class='img-neg'src="/static/pic.png">
</label>
</form>
<div class='name'><a href='http://www.website.com/{{ item.name }}'>@{{ item.name }}</a></div>
<div class='message'>{{ item.message }}</div>
<div class='picture'><img class='mess-picture' src="{{ url_for('static', filename=item.imgpath) }}"</img></div>
{% if item.points > 0 %}
<div class='voting-number-pos'>{{ item.points }}</div>
{% elif item.points < 0 %}
<div class='voting-number-neg'>{{ item.points }}</div>
{% else %}
<div class='voting-number-zero'>{{ item.points }}</div>
{% endif %}
</div>
{% endfor %}


This is the div I am trying to repopulate with my new returned JSON on scroll and append it to the bottom of body.

Answer

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.