atkat12 atkat12 - 3 months ago 50
Python Question

Flask: redirect(url_for()) returning html but not loading page

I am building a small web app in Flask, a code excerpt is below. Basically, I am trying to store some data in

startsession
and then move on to
tagpage
once this is achieved. But
redirect
is not working.

When I run
TEST 1
, it displays
hello, world
in the console but the main page looks the same.

When I run
TEST 2
, it displays the html in the console but the main page looks the same.

Here is what I have:

@app.route('/startsession', methods=['POST'])
def startsession():
_username = request.form['inputName']
session['user_name'] = _username
...
return redirect(url_for('tagpage'))


Then, either:

### TEST 1
@app.route("/tagpage")
def tagpage():
return "hello, world"


Or:

### TEST 2
@app.route("/tagpage")
def tagpage():
return render_template('tagpage.html', filename=filename)


Sample of what I see after clicking the button that triggers
startsession
:

enter image description here

How can I get the browser to actually go to
http://localhost:5000/tagpage
?

UPDATE:
Here is my JQuery script:

$(function(){
$("#btnStartSession").click(function(){
$.ajax({
url: '/startsession',
type: 'POST',
data: $('form').serialize(),
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});


});
});

Answer

I guess the screenshot shows the output of console.log and thus I conclude that the POST is done in javascript, probably jQuery (waiting for an answer from the asker).

If this is the case, this is the expected behavior. The POST is done and the javascript receives the redirect and GET's the redirected resource.

And the javascript is logging the html of the redirected resource.

If you want to redirect the browser you can either do this manually in the javascript (after the POST is done) using:

window.location = "/tagpage";

Or let the browser do it for you, in this case, the POST must be done through a <form>.

Comments