nmacc nmacc - 5 days ago 6
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__)

@app.route("/")
def index():
current_origin = jsonify(book())
return render_template('index.html', current_origin=current_origin)

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


and the corresponding JS looks like this:

$(document).ready(function() {
console.log("ready!");

$('#try-again').hide();

// gets values from flask
$.ajax({
type: "GET",
url: "/",
success: function(data) {
$('#results').append(data);
console.log(data);
},
error: function(error) {
console.log(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
$('#results').append(data)
to include .html(data), .text(data), etc. but am not understanding what I'm doing wrong here.

Answer

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

@app.route("/")
def index():
    return render_template('index.html')


@app.route("/get_book")
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.

Comments