Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hello everyone,

I want to authenticate my login page using javascript in asp.net .

if the user is authenticated then it should redirect to home page else it should say invalid login.

I have managed something like this but it is not working as desired.

my login control..
XML
<table style="font-size: 20px;" >

                  <tr>
                        <td>
                            Username
                        </td>
                        <td></td>
                        <td>
                            <%--<input type="text" runat="server" id="username" name="username"  style="height :20px; width :200px;"  />--%>
                            <asp:TextBox ID ="txtUsername" runat ="server" style="height :20px; width :130px;"  ></asp:TextBox>
                        </td>
                  </tr>
                    <tr>
                        <td></td>
                    </tr>
                    <tr>
                        <td>
                            Password
                        </td>
                        <td></td>
                        <td>
                            <%--<input type="password"  runat="server" id="password" name="password" style="height :20px; width :200px;"/>--%>
                            <asp:TextBox ID ="txtPassword" runat ="server" style="height :20px; width :130px;" textmode="Password"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                    </tr>
                    <tr>
                        <td>
                            <span id="resultspan"></span>
                        </td>
                        <td></td>
                        <td>
                           <input type="button" name="submit" id="submit" value="Submit" onclick="checkLoginDetails();"/>
                        </td>
                    </tr>
             </table>

<script type="text/javascript">

     var xmlhttp;
     function loadXMLDoc(url, cfunc) {
         if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
             xmlhttp = new XMLHttpRequest();
         }
         else {// code for IE6, IE5
             xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         if (xmlhttp != null) {
             xmlhttp.onreadystatechange = cfunc;
             xmlhttp.open("GET", url, true);
             xmlhttp.send();
         }
         else {
             alert("Page can not process");
         }
     }


     function checkLoginDetails() {
         // var username = $('#username').val();
         // var password = $('#password').val();
         var username = document.getElementById('<%= txtUsername.ClientID %>').value;
         var password = document.getElementById('<%= txtPassword.ClientID %>').value;
         var url = "";
         if ((username == null || username == '') && (password == null || password == '')) {
             alert("Please enter Username and Password.");
             return;
         } else if (username == null || username == '') {
             alert("Please enter Username.");
             return;
         } else if (password == null || password == '') {
             alert("Please enter Password.");
             return;
         }
         url = "AjaxFunctions.aspx?username=" + username + "&password=" + password + "&Action=login";
         loadXMLDoc(url, function () {
             if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                 
                
                     alert('Hi');
                     //document.getElementById("myDiv1").innerHTML = xmlhttp.responseText;
                     window.location = '<%= ResolveUrl("~/Home.aspx") %>';
                
                 
             }
             else {
                 alert('Invalid login');
             }
         });
     }
    </script>

my ajax function...

 private void Login()
    {
        try {

            sq = new SQLDataAccessHelper();
            string userName = Request.QueryString["username"];
            string password = Request.QueryString["password"];
            DataSet ds = new DataSet();
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@username", SqlDbType.NVarChar);
            param[0].Value = userName;
            param[1] = new SqlParameter("@password", SqlDbType.NVarChar);
            param[1].Value = password;
            ds = sq.ExecuteDataSet("usp_authenticate_user", param);
            if ((ds.Tables[0].Rows.Count != 0) && (ds.Tables.Count != 0) && (ds != null) && (ds.Tables[0].Rows[0]["Message"].ToString().ToLower() == "y"))
            {
                Session["Username"] = userName;
                
                //Response.Write(strXmlval);
                 //Response.Redirect("Home.aspx", false);
            }
            else if ((ds.Tables[0].Rows.Count != 0) && (ds.Tables.Count != 0) && (ds != null) && (ds.Tables[0].Rows[0]["Message"].ToString().ToLower() == "n"))
            {
               // string strXmlval = "<responseText>" + 0 + "</responseText>";
               // Response.Write(strXmlval);
            }

        }
        catch (Exception ex) { throw ex; }
        finally { }
            
                  
        
    }


now what happens is........with correct userid and password it goes to home page...but for wrong userid and password also it goes to home page...

and when i debugged javascript using alerts it gave me four times the alert box as 'Hi'

please help me how to make this thing possible...

regards,
krunal panchal
Posted

Your code is OK, it's just incomplete.

Because in your callback function:

Quote:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {


alert('Hi');
//document.getElementById("myDiv1").innerHTML = xmlhttp.responseText;
window.location = '<%= ResolveUrl("~/Home.aspx") %>';


}
else {
alert('Invalid login');
}

You don't handle the response. You just change the window.location no matter if the user/pass were correct or not.

in your C# code the response is quoted as remark:
Quote:
// string strXmlval = "<responsetext>" + 0 + "";
// Response.Write(strXmlval);


Cheers,
Edo
 
Share this answer
 
v2
Comments
krunalpanchalN 7-Feb-13 7:31am    
i have removed the comments but still it doesnt works..............

i want something that if the login is successfull then it should redirect to home page otherwise it should say invalid login..

please help me
Joezer BH 7-Feb-13 8:19am    
What you can do is either return an indication to the Javascript if the user pass is correct
OR

you can use the line :
Response.Redirect("Home.aspx", false);
that you have in the C# code to do the redirect.
AND in the JS remove the window.location command, because this way if the answer returns to the JS it will mean that the user and pass are incorrect.
krunalpanchalN 9-Feb-13 5:20am    
Thanks a lot it is done .... :)
Be careful here. It does not appear that you are sending the request with https, so you are exposing the user's credentials in clear text for all to see.
 
Share this answer
 

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