How to redirect using Flask and jQuery

I use Flask as my backend and jQuery for the personal project I'm working on.

To log in, I want to do this:

$.ajax({ type: "POST", data: JSON.stringify(body), //username and password contentType: 'application/json; charset=utf-8', url: "/login", success: successFunction, error: errorFunction, complete: completeFunction }); 

In errorFuction, I would tell the user that their username or password is incorrect, etc.

On the backend, my / login looks like this:

 @app.route("/login", methods=['GET', 'POST']) def login(): if(request.method == "POST"): #retrieve the username and password sent data = request.json if(data is None or not 'username' in data or not 'password' in data): abort(400) else: count = User.query.filter(User.username == data['username']).count() if(count == 0): abort(404) #that user doesnt exist else: passIsCorrect = User.query.filter(User.username == data['username'], User.password == data['password']).count() if(passIsCorrect): session['user'] = data['username'] return redirect(url_for('index')) else: abort(401) else: return render_template('login.html') 

However, on the client side, the browser does not redirect, and if I look in the response object in full function, I see that it will usually return from my route '/': 200 OK and the index.html template.

My question is:

Is there any way to intercept client redirects?

I assume the problem is that jquery is initiating the request, not the browser.

My first attempt to solve this problem was to build the answer myself using make_response and set the Location header, but this led to the same behavior. My current solution is to return 200, and then the client does window.location = "/" , but it seems to be hacked

+7
source share
2 answers

Forwarding to ajax calls does not work, browsers do not comply with them. Most people implement their own forwarding solution, returning 200 code and a redirect URL in a JSON response. See this question for some good examples.

As a side note, POST registration of the login form via ajax does not really give you much advantage, I would allow the browser to POST the form in normal mode, and then your function of viewing flacks redirects to a new page with success or redirects the login page to system on failure, possibly with a flash message to inform the user about the error.

+9
source

There is no reason to use redirection with ajax, because it will return redirected content (in your case, only content with an index endpoint). Thus, you can return a redirect link if everything is fine (status 200), and not a real redirect:

 return url_for('index') 

and process it with js:

 var successFunction = function (data) { // do something window.location = data; }; 
+6
source

All Articles