render_template does nothing after receiving ajax content (flask, python, javascript)

Tags: , , , ,



I am passing data with ajax to my python function when a condition is met:

        if (lesson.length === 0) {
            $.ajax(
                {
                    type:'POST',
                    contentType:'application/json',
                    dataType:'json',
                    url:'http://127.0.0.1:5000/result?value=' + errors ,
                    success:function(response){ document.write(response); }  
                }
            );
        }

I know that the information is correctly received, since I can see it in the terminal through print:

127.0.0.1 - - [19/Aug/2020 11:59:46] "GET /static/flexjava.js HTTP/1.1" 200 -
0
127.0.0.1 - - [19/Aug/2020 11:59:48] "POST /result?value=0 HTTP/1.1" 200 -

But python does nothing after the print() function. Render or redirect both don’t work, the browser stays just as it is even though the information was passed:

@app.route("/result", methods=["GET", "POST"])
def result():
    content = request.args.get('value')
    if "username" not in session or session["username"] == "guest":
        return redirect("/login")
    if request.method == "GET":
        return redirect("/")
    else:
        print(content)
        return render_template("finished.html")

Answer

You are not using ajax properly. You want to receive back a json response, not a complete web page.

Try:

$.ajax(
        {
            type:'POST',
            contentType:'application/json',
            dataType:'json',
            url:'http://127.0.0.1:5000/result?value=' + errors ,
            success:function(response){ 
                console.log(response);
                document.write(response); # not a good idea
                # I would use something like:
                # document.getElementById("myDiv").innerText = response.content;
            }  
        }
    );
    

Then:

from flask import jsonify

@app.route("/result", methods=["GET", "POST"])
def result():
    content = request.args.get('value')
    ...
    else:
        print(content)
        return jsonify(
            {
                "content": content
            }
        )

This functionality really does nothing, as you already have errors in the calling template. If you are trying to go to finished, you would do that in the ajax success callback:

success:function(response){ 
    console.log(response);
    window.location.replace(window.location.href + "finished");
}


Source: stackoverflow