nmacc nmacc - 1 year ago 194
Ajax Question

Flask Render Template Repeating HTML

I have a Flask app i'm integrating with JS. My app.py file looks like this:

import urllib
import requests
import time
from es import book

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

def index():
current_origin = jsonify(book())
return render_template('index.html', current_origin=current_origin)

if __name__ == "__main__":
app.run(host='', debug=True ,port=5000)

and the corresponding JS looks like this:

$(document).ready(function() {


// gets values from flask
type: "GET",
url: "/",
success: function(data) {
error: function(error) {

The console is printing the appropriate data from the call to
es import book
but the rendered page just keeps repeating the HTML with no data values (an endless repeat of HTML appended to the correct div but without the data I'm expecting). I tried several variations of
to include .html(data), .text(data), etc. but am not understanding what I'm doing wrong here.

Answer Source

I see what is happening. You need to separate the endpoints for rendering the page and returning the AJAX data. Try this:

def index():
    return render_template('index.html')

def get_book():
    return jsonify(book())

Then change the url component of your AJAX call:

url: "{{ url_for('get_book') }}",

jsonify() returns a Response object. render_template() uses jinja to render the html page. Your code keeps inserting the same source HTML document into itself, triggering an infinite loop. You should only use render_template() to render an HTML page and jsonify() to send data to XHR calls.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download