I am passing data with ajax to my python function when a condition is met:
JavaScript
x
12
12
1
if (lesson.length === 0) {
2
$.ajax(
3
{
4
type:'POST',
5
contentType:'application/json',
6
dataType:'json',
7
url:'http://127.0.0.1:5000/result?value=' + errors ,
8
success:function(response){ document.write(response); }
9
}
10
);
11
}
12
I know that the information is correctly received, since I can see it in the terminal through print:
JavaScript
1
4
1
127.0.0.1 - - [19/Aug/2020 11:59:46] "GET /static/flexjava.js HTTP/1.1" 200 -
2
0
3
127.0.0.1 - - [19/Aug/2020 11:59:48] "POST /result?value=0 HTTP/1.1" 200 -
4
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:
JavaScript
1
11
11
1
@app.route("/result", methods=["GET", "POST"])
2
def result():
3
content = request.args.get('value')
4
if "username" not in session or session["username"] == "guest":
5
return redirect("/login")
6
if request.method == "GET":
7
return redirect("/")
8
else:
9
print(content)
10
return render_template("finished.html")
11
Advertisement
Answer
You are not using ajax properly. You want to receive back a json
response, not a complete web page.
Try:
JavaScript
1
16
16
1
$.ajax(
2
{
3
type:'POST',
4
contentType:'application/json',
5
dataType:'json',
6
url:'http://127.0.0.1:5000/result?value=' + errors ,
7
success:function(response){
8
console.log(response);
9
document.write(response); # not a good idea
10
# I would use something like:
11
# document.getElementById("myDiv").innerText = response.content;
12
}
13
}
14
);
15
16
Then:
JavaScript
1
14
14
1
from flask import jsonify
2
3
@app.route("/result", methods=["GET", "POST"])
4
def result():
5
content = request.args.get('value')
6
7
else:
8
print(content)
9
return jsonify(
10
{
11
"content": content
12
}
13
)
14
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:
JavaScript
1
5
1
success:function(response){
2
console.log(response);
3
window.location.replace(window.location.href + "finished");
4
}
5