Why I cannot Login the using c# and mysql in ASP.net - javascript

I am beginner in developing a website using ASP.Net
Please Help me. so that i can pursue my career. Thanks in Advance
I am creating a login script using c# and I want to call it in javascript.
But it after I Logged in, The Login page will only refreshing.
And there is an exception said Exception thrown: 'System.InvalidOperationException' in System.Web.Extensions.dll
So here is my code :
HTML
<form>
<div class="form-group">
<input type="text" class="form-control material" id="username" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control material" id="password" placeholder="Password">
</div>
<button type="submit" id="btnLogin" class="btn btn-block btn-info text-uppercase waves">Login</button>
</form>
JAVASCRIPT:
$(document).ready(function () {
$("#btnLogin").click(function () {
var username = $("#username").val();
var password = $("#password").val();
AuthenticateUser(username, password)
});
});
function AuthenticateUser(username, password) {
var value = "{'email':'" + username
+ "','pass':'" + password
+ "'}";
$.ajax({
type: 'POST',
url: '../WebService/csLogin.asmx/loadEmployeeAccount',
dataType: 'json',
data: value,
contentType: 'application/json; charset=utf-8',
success: function (response) {
var cells = eval("(" + response.d + ")");
console.log(cells);
if (cells.length >= 1) {
window.location.href = "index.html";
} else {
alert("Invalid Email/Password");
document.getElementById("username").focus();
}
},
error: function (error) {
alert(JSON.stringify(error))
}
});
}
C#:
[WebMethod]
public string loadEmployeeAccount(string email, string pass)
{
List<Auth> mylist = new List<Auth>();
using (MySqlConnection connection = new MySqlConnection(connectionString()))
{
connection.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM user WHERE username = #email AND password = #pass", connection);
cmd.Parameters.Add("#email", MySqlDbType.VarChar).Value = email;
cmd.Parameters.Add("#pass", MySqlDbType.VarChar).Value = pass;
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 0;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
int user = 0;
if (dr["userType"].ToString() == "")
user = 1;
else
user = Convert.ToInt32(dr["userType"].ToString());
mylist.Add(new Auth
{
user_id = dr["user_id"].ToString(),
username = dr["username"].ToString()
});
}
dr.Close();
connection.Close();
}
JavaScriptSerializer jss = new JavaScriptSerializer();
string jsn = jss.Serialize(mylist);
return jsn;
}
And here is the image on the console.
Can someone help me with this?? any help will much be appreciated. Thanks

Okay, in order to achieve your functionality follow these steps:
In your AJAX, do the following to convert your value string as JSON and then send it to your WebMethod:
data: {"json": JSON.stringify(value)}
Then decorate your class with:
[System.Web.Script.Services.ScriptService]
to allow POST requests via AJAX to your WebMethod.
And then in your WebMethod, do the following to parse your JSON string that you received from your AJAX call:
[WebMethod]
public string loadEmployeeAccount(string json)
{
dynamic jsondata = serializer.Deserialize(json, typeof(object));
string username = jsondata["email"];
string password=jsondata["pass"]
//Your code here
}

it seems there is issue in passing value from ajax call please make change in your javascript function to call webmethod
function AuthenticateUser(username, password) {
var value = {'email':username,
'pass':password};
$.ajax({
type: 'POST',
url: '../WebService/csLogin.asmx/loadEmployeeAccount',
dataType: 'json',
data: JSON.stringify(value),
contentType: 'application/json; charset=utf-8',
success: function (response) {
var cells = eval("(" + response.d + ")");
console.log(cells);
if (cells.length >= 1) {
window.location.href = "index.html";
} else {
alert("Invalid Email/Password");
document.getElementById("username").focus();
}
},
error: function (error) {
alert(JSON.stringify(error))
}
});
}

I’m not familiar with pure ASP.NET, as I use MVC, but I guess they’re just the same under the hood, so this is a wild guess.
First thing, within your Ajax function you have to change the type of action from POST to GET, your error webpage is explicitly telling you you’re not supposed to send data through a POST action, after all.
type: ‘GET’
Second thing, i think the way you’re passing data to the web method is wrong: you’re passing a single literal object when your method is expecting two strings. By changing this, things should work as expected:
data: {
email: username,
pass: password
}
also, delete the dataType: ‘JSON’

Related

HTML value passed to WebService is showing NULL

I have a AJAX Web Serice that runs an SQL statment, which works.
I am trying to take an HTML value from my web page and use it as an additional variable in my query.
Here is how I am capturing that variable on my web page.
<div style="margin-left:0px">
<label>Enter Number here: </label><br>
<input type= text id="demo">
</div>
...and this is my Web Service call.
//Generate code
function Generate() {
var myGrid = $('#jqquotes'),
selectedRowId = myGrid.jqGrid('getGridParam', 'selrow');
docid = myGrid.jqGrid('getCell', selectedRowId, 'docid');
document.getElementById("demo").innerHTML = document.getElementById("demo").value;
alert(document.getElementById("demo").value);
var quotenum = document.getElementById("demo".value);
if (confirm('Are you sure you want to generate a quote?')) {
$.ajax({
url: '/WebService1.asmx/Generate',
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "GET",
data: { docid: docid, quotenum: JSON.stringify(quotenum) },
success: function () {
//Get selected
var grid = $("#jqquotes");
var rowKey = grid.jqGrid('getGridParam', "selrow");
//Refresh grid
$('#jqquotes').trigger('reloadGrid');
//Set Selected
setTimeout(function () {
jQuery('#jqquotes').jqGrid('setSelection', rowKey);
}, 200);
}
});
} else {
return false
}
}
The alert box correct displays the HTML value from the box id "Demo"
But the WebService fails, saying the value is NULL, JSON reponse is:
Message "The parameterized query '(#docid nvarchar(5),#quotenum nvarchar(4000))UPDATE [dbo].[quote' expects the parameter '#quotenum', which was not supplied."
...and the GET URL shows the value as NULL
https://localhost:44338/WebService1.asmx/Generate?docid=10146&quotenum=null
Any help greatly appreciated.
I think the problem is here:
var quotenum = document.getElementById("demo".value);
This should be
var quotenum = document.getElementById("demo").value;
as in the line above it.

Trying to display 4 concate item in dropdownlist from database

I'm trying to bind and display 4 concatenate item in dropdownlist using ajax.
Like this eg. (127,CoilWt,1,KGS ) one of the value in dropdownlist should appear like this.from database.
In database i am selecting
`select CODE_VALUE,CODE_DESC,CODE_SUB_VALUE,CODE_SUB_DESC FROM TCODE
html part
<td><select class='form-control' id='Certific'><option value='' disabled='disabled' selected='selected'>Please select a name</option></select></td>
script part
$(function () {
$.ajax({
type: "POST",
url: "TDC.aspx/GetCertificate",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var Certific = $("[id*=Certific]");
Certific.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(r.d, function () {
Certific.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
});
});
c# side
public class GetCertificate
{
public int ID { get; set; }
public string Code_Desc { get; set; }
}
[WebMethod]
public static List<GetCertificate> GetCertificate()
{
string connStr = ConfigurationManager.ConnectionStrings["conndbprodnew"].ToString();
OracleConnection objconn = new OracleConnection(connStr);
string prop_name, tdc_property = "", qry = "";
qry = "SELECT CODE_DESC from tdc_product1 ";
OracleCommand objFetchCmd = new OracleCommand(qry, objconn);
List<GetCertificate> Certificate = new List<GetCertificate>();
objconn.Open();
OracleDataReader ReadData = objFetchCmd.ExecuteReader();
while (ReadData.Read())
{
GetCertificate.ID = ReadData["ID"].ToString();
GetCertificate.CODE_DESC = ReadData["CODE_DESC"].ToString();
}
return Certificate;
}
Where is the mistake i am trying like this but getting error at GetCertificate.ID .Any idea would be appreciated.
I guess you're making mistake at:
GetCertificate.ID = ReadData["ID"].ToString();
GetCertificate.CODE_DESC = ReadData["CODE_DESC"].ToString();
GetCertificate seems to be a type not a instance of object.
You should try something like:
Certificate.Add(new GetCertificate { ID = ReadData["ID"].ToString(), CODE_DESC = ReadData["CODE_DESC"].ToString() } );
Please be aware that I wrote this without any IDE, so there could be typo/syntax error, but you get the idea.
Small hint: Of course there're plenty of room for code refactor in your code (e.g. rename Certificate to Certificates), but that is another topic.

How to store the username in the URL while working on Ajax calls

I am new to front-end and was trying to create a Login page which had username and password to login. I wanted to store the Logged-In username in the URL, so had to use the PUT method in the AJAX call. But my login is always failing as I am unable to pass the correct username attribute in the URL, Please see the below code to refer:
Again how to pass the {username} in the URL, you can see the below URL in ajax call where I have this username attribute.
jQuery:
$("#login-user").validate({
submitHandler: userLogin
});
function userLogin() {
var data = $("#login-user").serialize();
if (userName != '' && password != '')
{
$.ajax({
url: 'http://www.website.com/database/tableusers/{username}/login',
type: 'PUT',
data: data,
success: function(data) {
if (data == 0) {
result.html('<span class="error">Incorrect username or password</span>')
} else if (data == 1) {
window.location = "tothepage.html";
} else {
$("#error").fadeIn(1000, function() {
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> ' + data + ' !</div>');
});
}
}
});
}
}
You haven't defined either userName or password. data is correct, though.
Also, it might be right for your backend code, but you probably would have to use POST (type).
So, you're missing this:
function userLogin() {
var data = $("#login-user").serialize();
var userName=$("#userNameInputID").val();
var password=$("#passwordInputID").val();
if (userName != '' && password != '')
{
$.ajax({
url: 'http://www.website.com/database/tableusers/'+userName+'/login', //just concatenate userName here (case sensitive)
type: 'PUT',
data: data,
....
Keep the username as a variable.
var url = 'http://www.website.com/database/tableusers/'+username+'/login';
Build the URL first and store it in a variable, then use the variable in the AJAX call.
For instance:
var userUrl = 'http://www.website.com/database/tableusers/' + userName + '/login';
$.ajax({
url: userUrl,
type: 'PUT',
data: data,
success: function(data) {
You just need to access the username and password variables from your data object and define them as vars
function userLogin() {
var data = $("#login-user").serialize();
var username = data.username;
var password = data.password;
if (username != '' && password != '')
...
Also, you can inject the variable for username into the URL by adding it with the + string operator
url: 'http://www.website.com/database/tableusers/' + username + '/login';

Check the value of a text input field with ajax

I have a website where the log ins are screen names. On the create user form I want to be able to have ajax check if a screen name exists already as it is typed into the form.
This is the HTML form input field
<label for="screenName">Screen Name:
<input type="text" class="form-control" name="screenName" id="screenName" size="28" required>
<div class="screenNameError"></div>
A message should be displayed in the <div class="screenNameError"></div>line if the username matches the database.
This is my Jquery code for this.
$(document).ready(function(){
if ($('#screenName').length > 0){
var screenName = $("input").keyup(function(){
var value = $(this).val();
return value;
})
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
This is the PHP file that gets called to make the DB query
$screenName = $_POST['Screen_Name'];
$screenNameSQL = "SELECT Screen_Name FROM Users WHERE Screen_Name = '$screenName'";
$result = $my_dbhandle->query($screenNameSQL); //Query database
$numResults = $result->num_rows; //Count number of results
$resultCount = intval($numResults);
if($resultCount > 0){
echo "The username entered already exists. Please a different user name.";
}
For some reason my Jquery is not firing when I type the username in the form :/
Thanks in advance
Try changing your jQuery to this -
$(document).ready(function() {
$('#screenName').keyup(function() {
var value = $(this).val();
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
});
});
However you probably want to minimise the number of ajax requests being made so I would advise putting your ajax request into a setTimeout functon and clearing it with each subsequent keypress. -
$(document).ready(function() {
var ajaxRequest;
$('#screenName').keyup(function() {
var value = $(this).val();
clearTimeout(ajaxRequest);
ajaxRequest = setTimeout(function(sn) {
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
}, 500, value);
});
});
if ($('#screenName').length > 0){
You should change it with
if ($('#screenName').val().length > 0){
OR
var name = $('#screenName').val();
if(name.length >0) {...
not sure about the syntax...
Add an event on keyup like this :
Edit
$("#screenName").on("keyup",function(){
var screenName=$(this).val();
if(screenName!='')
{
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
JsFiddle
Your ajax call should be inside the keyup handler.

LogIn Page Using JQuery

Before 3 days the code was working fine. But now its not.
please point out my mistake as i am new to JQuery.
I debugged it, and found out that debugger is not entering inside success method of ajax. and not even going to CS file.
Code of Jquery-
<script type="text/javascript">
$(document).ready(function () {
$('#btnSubmit').click(function () {
alert('b');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "admin.aspx/LogIn",
dataType: "json",
data: "{'name':'" + $('#txtfn').val() + "','password':'" +$('#txtln').val() + "'}",
success: function (data) {
alert(data);
var obj = data.d;
alert(obj);
alert(data.d);
if (obj == 'true') {
$('#txtfn').val('');
$('#txtln').val('');
alert("dasdsad");
window.location = "home.aspx";
alert("success");
}
else if (obj == 'false')
{ alert("errorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"); }
},
error: function (result) {
alert(data);
alert("aaaaaaafgdgfdfgsfgfhffghgfhgfhfghfghfhfghfhfghgfhgfhgfhgfhfghfghgfhgfhgf");
alert(result);
}
});
});
});
</script>
</head>
<body>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form id="f1" runat="server">
<input type="text" id="txtfn" placeholder="name" />
<input type="text" id="txtln" placeholder="Password" />
<input type="submit" id="btnSubmit" value="Log in" />
</form>
</div>
</body>
Code-
[WebMethod]
public static string LogIn(string name, string password)
{
string retMessage = string.Empty;
string constr = ConfigurationManager.ConnectionStrings["oltest_conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string Query = "select * from profile where name=#pname and password=#pwd";
using (SqlCommand cmd = new SqlCommand(Query, con))
{
cmd.Parameters.AddWithValue("#pname", name);
cmd.Parameters.AddWithValue("#pwd", password);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
//retMessage = "home.aspx";
retMessage = "true";
}
else
{
retMessage = "false";
}
}
return retMessage;
}
}
You just need to remove
alert('b');``
on your jquery code
try adding a
return false
at the end of the ajax call
Hi change your submit button to button.
<input type="button" id="btnSubmit" value="Log in" />
data: {name: $('#txtfn').val() ,password: $('#txtln').val()},
I updated my answer:
your ajax call is not executed because form is submitted, this code will prevent submission
$("#f1").submit(function (e) {e.preventDefault();})
place it before $('#btnSubmit').click(function () {
better way will be place your code inside
$("#f1").submit(function (e) {
e.preventDefault();
// here place content of $('#btnSubmit').click(function () {( )}
})
Please ensure JSON data /parameters accepted by your web method and it returning proper true/false without any exception/error.
You can do it by debugging in firebug and Visual Studio.

Categories

Resources