Render template in Flask from ajax call

Viewed 1771

Having a tough time with this. I'm sending some data via Ajax to my Flask server route where it is being processed, with hopes to then render a new template with the processed data. The data seems to be flowing fine from my Javascript to my Flask server. (I am using JSGlue for Flask.url_for.) But as soon as it gets to "return render_template" it just dies. I get no traceback errors or anything. I've tried print() and console.log all over the place to get some kind of idea of what is killing it, but so far I've come up empty. Am I missing something obvious?

mypage.js

let c_list = [1,2,3....];

    $.ajax({
        url: Flask.url_for('get_genres'),
        type: "POST",
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(c_list),
        success: function (data) {
            console.log(data);
        }
    })

init.py

@app.route('/get_genres', methods=["GET", "POST"]
def get_genres():
    if request.method == "POST":
        categories = request.json
        c = Querybuilder()
        genres = c.genres_from_c(categories)
        return render_template("genres.html", genres=genres)

index.html

<head>

    {{ JSGlue.include() }}
</head>

<body>

    {% block body %}
    {% endblock %}
</body>

genres.html

{% extends "index.html" %}
{% block body %}
<div class="genre_list">
    {% for genre in genres %}
    <a href="#" src="{{ genres[genre] }}" class="unclicked" onclick="toggleClicked(this)">
        <p>{{ genre }}</p></a>
    {% endfor %}
    <a href="#" onclick="getGenreId()">NEXT</a>
</div>
{% endblock %}
1 Answers

After A LOT of digging around, I finally managed to find a solution to this issue. Adding a success function to the ajax call that redirects to another route.

mypage.js

$.ajax({
        url: Flask.url_for('genre_picks'),
        type: "POST",
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(genres),
        success: function(response) {
            window.location.href = response.redirect
        }
    });

init

@app.route('/genre_picks', methods=["POST", "GET"])
def genre_picks():
    if request.method == "POST":
        genres = request.json
        return jsonify({'redirect': url_for("example", path=genres)})

@app.route('/example/<path>')
def example(path):
    genres = path
    return render_template("example.html", genres=genres)
Related