0

I made a script that allows a user to login I used python flask microframework jquery but the problem that if I filled the fields user and password it will not have a passage to another page which I have already specified in the method if the data are loginuser correctent. And the second problem is the appraition data in the url.

login1.html

<!DOCTYPE html>
<!--[if (gte IE 9)|!(IE)]><!--> <html lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<title>login</title>
<link href="static/css/style.css" rel="stylesheet">
<script src="static/js/jquery-1.9.0.js"></script>
<script src="static/js/script.js"></script>
</head>
<body>
<div class="container">
    <section id="content">
        <form class="form-signin" role="form">
            <h1>Login Form</h1>
            <div> 

                <input type="text" id="txtUsername" placeholder="Username" name="username"  required autofocus>
                                <input type="password" id="txtPassword" placeholder="Password" name="password" required autofocus>
                               <input class="btn btn-default" type="submit" value="Login">

                      </div>
        </form><!-- form -->
        {% if error %}
                    <p class="error"><strong>Error:</strong> {{ error }}
                {% endif %}
    </section><!-- content -->

</div><!-- container -->
</body>
</html>
$(function(){
    $('submit').click(function(){

                var user = $('#txtUsername').val();
        var pass = $('#txtPassword').val();
        $.ajax({
            url: '/loginuser',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response){
                console.log(response);
            },
            error: function(error){
                console.log(error);
            }
        });
    });
});

this script.js. and app.py

@APP.route('/login')
def login1():

      return render_template('login1.html')


# route for handling the login page logic

@APP.route('/loginuser', methods=['POST'])
def login():

    error = None
    con = mdb.connect('localhost','testuser', 'test623', 'secure')
    #con= mdb.connect(host="x.x.x.x", port=3306, passwd="root", db="se")
    cur = con.cursor()
    cur.execute("SELECT * FROM ADMIN")
    rows = cur.fetchall()
    login=False
    ########recuperer la liste des admin de la BD ADMIN
    for row in rows:
             if request.form['username'] == row[0] and  request.form['password'] == row[1]:
                login=True


    con.close
    if login ==False:
             error = 'Invalid Credentials. Please try again.'
             return render_template('login1.html', error=error)

    else:
             return render_template('mon.html', error=error)
davidism
  • 121,510
  • 29
  • 395
  • 339
kaio
  • 131
  • 1
  • 10

2 Answers2

0

As far as I understand the question, you shouldn't use AJAX here. When using AJAX you will not be redirected to a new page rendered by

@APP.route('/loginuser', methods=['POST'])
def login():
   ...

You will rather get this page in AJAX response and can access it in your success callback (first parameter).

If you want to go with AJAX here, you should change your login response to something, that can be conveniently consumed by JavaScript, for example JSON response, that contains login attempt result. Something like

{
    "result": "success",
    "details": "User has been successfully logged in"
}

or

{
    "result": "error",
    "details": "Login or password is incorrect"
}

You should return this JSON instead of your login form template

(instead of this)

         return render_template('login1.html', error=error)

Then parse it in your success/error callback and make a decision on how to display this information to the user.

$(function(){
    $('submit').click(function(){

                var user = $('#txtUsername').val();
        var pass = $('#txtPassword').val();
        $.ajax({
            url: '/loginuser',
            data: $('form').serialize(),
            type: 'POST',
            dataType: 'json',
            success: function(response){
                if (response.result == "success") {
                    alert("You have been logged in!");
                } else {
                    alert(result.details);
                    // You can do something much more complex than 'alert' here
                    // E.g, you can add a DOM element with an error message
                }
            },
            error: function(error){
                console.log(error);
            }
        });
    });
});

Sorry, but I could not understand your second question...

  • Leonvich is what I have to change the .js file as you said or how I can do to make the call from another page can succeed. thanks – kaio Apr 10 '15 at 17:59
  • I tried to say that if you use AJAX to make a call, it does NOT refresh the current page in browser. It only retrieves the HTTP response from your server and gives you access to it in your ```success``` and ```error``` functions. So, if you just make an AJAX call, you'll not see any changes on the page. You should perform them explicitly in your ```success``` callback by writing some JS code. And as I said, HTML response is not a best format for passing data via AJAX, in this case it's better to use JSON or XML. – Maxim Leonovich Apr 10 '15 at 18:30
0

Well, you cannot select an element just by attribute only. The ajax function is not called. Give the submit button an id and it will work.

For example:

change this line

<input class="btn btn-default" type="submit" value="Login">

to

<input class="btn btn-default" id = "submitButton" type="submit" value="Login">

and the javascript to

 $('#submitButton').click(function(){.... });
gopiariv
  • 454
  • 7
  • 9