I have just change your Success function in Ajax Call
<script type="text/javascript">
$(function () {
$("[id*=btnlogin]").bind("click", function () {
var user = {};
user.Username = $("[id*=txtUsername]").val();
user.Password = $("[id*=txtPassword]").val();
$.ajax({
type: "POST",
url: "CS.aspx/ValidateUser",
data: '{user: ' + JSON.stringify(user) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
}
});
return false;
});
});
</script>
Here my page Name is CS.aspx .
I have pasted your code and created a sample.
Here is the HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=btnlogin]").bind("click", function () {
var user = {};
user.Username = $("[id*=txtUsername]").val();
user.Password = $("[id*=txtPassword]").val();
$.ajax({
type: "POST",
url: "CS.aspx/ValidateUser",
data: '{user: ' + JSON.stringify(user) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
}
});
return false;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
Username:
</td>
<td>
<asp:TextBox ID="txtUsername" runat="server" Text="" />
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnlogin" Text="Log In" runat="server" />
</td>
</tr>
</table>
</form>
</body>
</html>
Namespace
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
C#
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string ValidateUser(Users user)
{
int userId = 0;
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Validate_User"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", user.Username);
cmd.Parameters.AddWithValue("@Password", user.Password);
cmd.Connection = con;
con.Open();
userId = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
}
string IsValidate = string.Empty;
switch (userId)
{
case -1:
IsValidate = "Username and/or password is incorrect.";
break;
case -2:
IsValidate = "Account has not been activated.";
break;
case -3:
IsValidate = "Login Successfully.";
break;
}
return IsValidate;
}
public class Users
{
public string Username { get; set; }
public string Password { get; set; }
}
}
Now If you are not getting any then you need to check your Page Name and Web Method name are correct or not.