Click here to Skip to main content
15,889,854 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello! So i have a login form with user, pass and a button for login. On this button i want to put a JavaScript listener and when clicked to fire a $.ajax() function who sends
a request to the login page and then return a json response with 2 fields: error(failed) and msg(user/pass ok). When the ajax ends, the success function must display on the page the value from msg and if there is no error redirect to home page.
i suppose that in some way i need to verify the user/pass with what i have in the database, i just don't know how to do it.
i currently use sessions for my authentications and it works just fine but now my new task is to change it.
i tried something below the problem is i don't know how to do the validation with the database to see if the user and password are correct.
please help me with some ideas.
Thank you

What I have tried:

This is my table
 <table style="background-color:#f1f1f1">
             <tr>
                 <td><asp:Label runat="server" ID="lbl1" Font-Bold="true" ForeColor="Red"/></td>
             </tr>
           
             <tr>
                 <td><asp:Label runat="server">Username</asp:Label></td>
                 <td><asp:TextBox runat="server" ID="txtUser" placeholder="Username"/></td>
                 <td><asp:RequiredFieldValidator ID="rfvUser" runat="server" ControlToValidate="txtUser" ErrorMessage="*" ForeColor="Red" Font-Bold="true"  ValidationGroup="LoginInfo"/></td>
             </tr>
             <tr>
                 <td><asp:Label runat="server">Password</asp:Label></td>
                 <td><asp:TextBox runat="server" ID="txtPass" TextMode="Password" placeholder="Password"/></td>
                 <td><asp:RequiredFieldValidator ID="rfvPass" runat="server" ControlToValidate="txtPass" ErrorMessage="*" ForeColor="Red" Font-Bold="true"  ValidationGroup="LoginInfo"/></td>
             </tr>
             
             <tr >
                 <td></td>
                 <td><asp:Button runat="server" Text="Login" ID="btnLogin" CssClass="button" Width="210"  OnClick="btnLogin_Click" ValidationGroup="LoginInfo"/></td>
             </tr>
</table>


Here what i have been trying :

<script>
$(document).ready(function myfunction () {
                $('#btnLogin').click(function () {
                    var user = $('#txtUser').val();
                    var pass = $('#txtPass').val();

                    if (user != '' && pass != '') {
                        $.ajax({
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            url: "Login.aspx/InsertData",
                            data: {user: txtUser, pass: txtPass},
                            dataType: "json",
                            success: function (data) {
                                var obj = data.d;
                                if (obj == 'true') {
                                    $('#txtUser').val('');
                                    $('#txtPass').val('');
                                    $('#lbl1').html("Login Successfully");
                                    // window.location = "Default.aspx";??
                                }
                            },
                            error: function (result) {
                                $('#lbl1').html("Wrong username or password");
                               
                            }
                        });
                    }
                    else {
                        $('#lbl1').html("Please fill all fields");
                        return false;
                    }
                });
                });
          
        </script>


and in my aspx.cs maybe something like :

[WebMethod]
   public static string InsertData(string user, string pass)
   {
       string msg = string.Empty;
       using (MySqlConnection conn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString))
       {
           using (MySqlCommand cmd = new MySqlCommand("select * from useri where Username=@Username and Password=@Password", conn))
           {
               conn.Open();
               cmd.Parameters.AddWithValue("@Username", user);
               cmd.Parameters.AddWithValue("@Password", pass);
               int i = cmd.ExecuteNonQuery();
               conn.Close();
               if(i==1)
               {
                   msg = "true";
               }
               else
               {
                   msg = "false";
               }
           }
       }
       return msg;

   }
Posted
Updated 11-Jan-17 8:14am
Comments
[no name] 4-Jan-17 10:59am    
If you do not know how, where did this insecure code come from to begin with?
"help me with some ideas", ideas for what? You didn't ask a question or describe a problem. Do some research on how to securely store passwords in a database.
Member 12869977 5-Jan-17 2:44am    
The code came from the many tutorials i have been watching and still watch about ajax jquery and how to send json because obviously i just began learning. The passwords are secured in my initial code they are encrypted. This is just a example i have been trying to eventually get the task done. And i needed some ideas for how to make this a working code. Currently is not working. Sorry if i didn't make myself clear with what i needed
F-ES Sitecore 4-Jan-17 11:06am    
What's wrong with the code you have?

As an aside using ajax for this is pointless, just use a normal form. Ajax is to reduce web traffic and aid user experience but if I am taken to a different page after I login then what advantage have I gained from ajax apart from now needing js enabled to log in?

Edit: having looked at the sql code ExecuteNonQuery is for when you don't care about the result, so an update, insert or delete. You want to know how many records are returned so you could change the sql to

select count(*) from ...

then use ExecuteScalar instead of ExecuteNonQuery (google for syntax on how to use, you'll need to cast the result), or leave the sql as it is and use ExecuteReader and do something like

var dr = cmd.ExecuteReader();
if (dr.Read())
{
// login successful
}
Member 12869977 5-Jan-17 2:38am    
Well the current code doesn't work because the message never returns true, and it doesn't login and i know i am doing something wrong that is why i posted here. I am rather new to jquery ajax and i don't know what the advantage is but this is the task i have been given so .. i will change the sql thank you for your suggestion

1 solution

Kudos for using parameters but a big problem in the code is that you store the password as plain text. This opens up all passwords to people who can see the database.

Instead you should store only the hashed password and each time a user logs in, you test if the stored hash is the same as the newly calculated hash. This way you can check if the password is correct but you don't know what it actually is. For more information see Password Storage: How to do it.[^]

When you have done that you should change the web method to actually fetch the user info. Currently you execute non query which is used in manipulation statements or procedures. To see if the record really exists use SqlCommand.ExecuteReader Method (System.Data.SqlClient)[^]. If the reader returns a row, the login is done with correct username and password and if not, then inform the calling side.
 
Share this answer
 
Comments
Member 12869977 5-Jan-17 2:32am    
Thank you for your answer. Yes i know about hashed passwords in my initial code they are stored as md5 passwords.. what i posted above is what i have been trying and (of course when i will make it work i will encrypt the passwords) because like i said i need to change from the onclick event in the aspx.cs page as such that the button doesn't make a full postback, put a js listener onclick and use ajax to return json values

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900