1

So I've been working in Flask and ran into an irritating problem. I'm creating a website and using the redirect function the website doesn't switch pages. Each place I'm attempting to go to can render_template() when not called via redirect. Here's my code (yes, the hashed_password isn't hashed and I should probable redirect to next, but these are are problems for another day):

@app.route('/logIn',methods=['Get', 'Post'])
def logIn():
    _name = request.form['inputName']
    _password = request.form['inputPassword']
    # _hashed_password = bcrypt.hashpw(_password, bcrypt.gensalt( 12 ))
    _hashed_password = _password

    conn = mysql.connect()
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM tbl_user WHERE user_name = '" + _name + "'")

    user = cursor.fetchone()
    print(user[0])

    if len(user[2]) is not 0 and user[3] == _password:

        active_user = User(user[0])
        login_user(active_user)
        return (redirect(url_for('home')))
    else:

        return json.dumps({'message': 'Username or Password not correct'})


@app.route('/Home')
@login_required
def home():
    return render_template("home.html")

This all works with a html and js background. The HTML doesn't have any code, only contains the button to be clicked (though if it'll help I can post the html). The JS looks like this for the login button:

$(function() {
    $('#btnLogIn').click(function() {

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

});

Finally, the output spits back the html for the Home page, the one I want to be rendering in the browser (this is the output):

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Python Flask Bucket List App</title>
      <script src="static/js/jquery-3.3.1.min.js"></script>
      <script src="static/js/logout.js"></script>
  </head>

  <body>
   <form class="form-signout">
       <button id="btnLogOut" class="btn btn-lg btn-primary btn-block" type="button">Log Out</button>
   </form>
  </body>

</html>

I've been looking everywhere. Also, adding /Home after the local host domain calls the same GET as the one called after clicking the button and successfully loads the page. If anyone knows how to do this with loading the "next" url, that would be even better.

Michel
  • 4,076
  • 4
  • 34
  • 52
  • No sure it would help, but did you try using `url: '{{url_for(/login)}}'` in your ajax function? – Daniel da Rocha Mar 27 '18 at 05:28
  • instead of console.log(response), try $("body").html(response) and see if it changes anything ? – Rambarun Komaljeet Mar 27 '18 at 05:40
  • @RambarunKomaljeet That sort of worked! That rendered the new html! Unfortunately it stays in the previous link? I don't know how to describe it. It doesn't redirect to /Home, but has that html. – Sam Rosenberg Mar 27 '18 at 05:57
  • @SamRosenberg I know what you mean ;) . Its because that's how ajax works. Try using a javascript redirect in the success function instead of the $("body").html. ( Not sure if that would work though ) – Rambarun Komaljeet Mar 27 '18 at 06:02
  • @RambarunKomaljeet Hmm. Still having trouble. I can't replicate it for logging out, and it still doesn't manage to redirect the actual url. I still can't understand why redirect doesn't work as intended. – Sam Rosenberg Mar 27 '18 at 06:29
  • @SamRosenberg just found this. https://www.w3schools.com/xml/ajax_intro.asp. Ajax updates a page without reloading it, so i guess no redirection when using ajax :x – Rambarun Komaljeet Mar 27 '18 at 06:33
  • Also check this: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xiv-ajax good tips on ajax... – Daniel da Rocha Mar 27 '18 at 07:57

1 Answers1

0

Try to use trailing slash in route description, because in opposite case Flask returns 302 redirect by default that can't be handled by your JS code, so try to use this:

@app.route('/login/',methods=['GET', 'POST'])

@app.route('/home/')

instead of this

@app.route('/logIn',methods=['Get', 'Post'])

@app.route('/Home')

I suspect this can be the reason of the issue, but I didn't test it.

P.S.

1) Do not use such SQL queries:

cursor.execute("SELECT * FROM tbl_user WHERE user_name = '" + _name + "'")

due to possible SQL injections vulnerabilities. Use "prepared" values instead:

cursor.execute("SELECT * FROM tbl_user WHERE user_name = %s", [name])

2) Dont return JSON by this way:

return json.dumps({'message': 'Username or Password not correct'})

Use jsonify instead:

from flask import jsonify

response = jsonify(message='Username or Password not correct')
Artsiom Praneuski
  • 2,259
  • 16
  • 24