简体   繁体   中英

AJAX not changing/redirecting from login page to dashboard [flask backend]

I am using the post method for the login. My ajax function sends the data successfully to my flask backend server [I know because it returns a response to my ajax]. Supposedly, after receiving the respnse from the backend, my ajax success handler will navigate/redirect to the dashboard page but IT DOES NOT! How do I make it navigate/redirect to another page/url?It returns a 200 status code so I do not know why it does not display the dashboard page.

WHAT I HAVE TRIED:

I have tried using window.location.href, window.location.replace but to no avail, still it does not work. I have also tried changing the method to GET but its still the same. I have also set async to false because ajax would not post if I would not set it to false .

AJAX

$.ajax({
    type: "POST",
    url: 'http://127.0.0.1:5000/processlogin',
    data: JSON.stringify(loginobject),
    contentType: "application/json;charset=utf-8",
    async: false,
    success: function (resp) {
        window.location.href = ("http://127.0.0.1:5000/dashboard");
    },//success
    failure: function (resp) {
        alert(resp.message);
    }

});

backend flask functions This functions work 100%. Already tested it with POSTMAN. I have also queried the database using my stored procedure and it does well.

This displays the login form

@app.route('/', methods=['GET','POST'])
def login():
    return render_template('login.html')

This processes the ajax's sent data. In short this is the function ajax is communicating with

@app.route('/processlogin', methods=['POST'])
def processlogin():
    loginobject = request.get_json(force=True)
    username = loginobject['username']
    password = loginobject['password']

    try:
        dbpassword = callstoredproc("getpassword", (username,))[0][0]
        if dbpassword == 'null':
            return jsonify({'status':'error', 'message':'Username does not exist!'})
        elif bcrypt.verify(password, dbpassword) == True:
            return jsonify({'status':'ok'})
    except Exception as e:
        print(e)

And this is what I am trying to display: the dashboard html

@app.route('/dashboard', methods=['GET', 'POST'])
def dashboard():
    return render_template('dashboard.html')

Remove the curved brackets and try again:

 
 
 
  
  window.location.href = "http://127.0.0.1:5000/dashboard";
 
  

It works also with curved brackets so just be sure that your response arrive correctly to the success callback.

See also best answer on SO .

It should also be error instead of failure as error callback.

error: function (resp) {
    alert(resp.message);
}

jsfiddle Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM